Update and Delete a User Account in ASP.NET Identity

How to Update and Delete a User Account in ASP.NET Identity

In this article, I am going to discuss How to Update and Delete a User Account in ASP.NET Identity with Examples. Please read our previous article where we discussed Creating a User Account in ASP.NET Identity.

Update a User Account in ASP.NET Identity

In order to update an existing user account in ASP.NET Identity, we need to use the Update or UpdateAsync method.

Update or UpdateAsync Method:

The Update or UpdateAsync method in ASP.NET Identity updates the user passed as a parameter to the method and returns the result of the operation as an IdentityResult object as follows:

IdentityResult result = UserManager.Update(UserToEdit);

IdentityResult result = await UserManager.UpdateAsync(UserToEdit);

As we already discussed the UserManager is responsible for performing the user-related operations. So, here, you can see in the above code, the Update or UpdateAsync method is called by the UserManager instance which is responsible for performing the user-related operations. In this case, it is going to update the user information.

UserManager:

We use the GetUserManager method to get the ApplicationUserManager instance from the OWIN context as follows.

ApplicationUserManager UserManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();

We use the ApplicationUserManager instead of the UserManager in order to use the default validation logic for usernames and passwords configured in the IdentityConfig.cs file. So, if you go to the IdentityConfig.cs file, then you will see that ApplicationUserManager is inherited from the UserManager class as shown in the below image. The point that you need to remember is within the Create method of ApplicationUserManager class, it configures the validation logic for usernames and passwords.

How to Update and Delete a User Account in ASP.NET Identity

Namespaces

In order to use the GetUserManager method, the Update method, and the IdentityResult object, we have to include the following namespaces :

using Microsoft.AspNet.Identity;

using Microsoft.AspNet.Identity.Owin;

Example to Update a User in ASP.NET Identity:

Let us create a model with the name EditUserViewModel.cs within the Models folder. Once you create the EditUserViewModel.cs class file, then copy and paste the following code into it. This is going to be the model for updating the user data.

using System.ComponentModel.DataAnnotations;
namespace AspNetIdentityWithNewProject.Models
{
    public class EditUserViewModel
    {
        public string UserId { get; set; }

        [Display(Name = "Username")]
        [Required]
        public string UserName { get; set; }

        [Display(Name = "First name")]
        public string FirstName { get; set; }

        [Display(Name = "Last name")]
        public string LastName { get; set; }

        [Display(Name = "Email")]
        [Required]
        [EmailAddress]
        public string Email { get; set; }

        [Display(Name = "Phone number")]
        [Phone]
        public string PhoneNumber { get; set; }
    }
}
Adding UpdateUser Action Methods in Home Controller

Let us add the following two UpdateUser action methods to our HomeController. One is the HTTPGet Method and the other one is the HTTPPost method.

HTTPGet UpdateUser Method:

The HTTPGet UpdateUser method will accept the UserId which we want to update. It will then retrieve the user information from the database by using the ApplicationUserManager instance and then hand over the data to the corresponding view.

// GET: /Home/UpdateUser
[HttpGet]
public ActionResult UpdateUser(string UserId)
{
    //Creating an Instance of EditUserViewModel
    EditUserViewModel model = new EditUserViewModel();

    //Create an instance of ApplicationUserManager class as we want to fetch the user details
    ApplicationUserManager UserManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();

    //Fetch the User Details by UserId using the FindById method
    ApplicationUser UserToEdit = UserManager.FindById(UserId);

    //If the user exists then map the data to EditUserViewModel properties
    if (UserToEdit != null)
    {
        model.UserId = UserToEdit.Id;
        model.UserName = UserToEdit.UserName;
        model.FirstName = UserToEdit.FirstName;
        model.LastName = UserToEdit.LastName;
        model.Email = UserToEdit.Email;
        model.PhoneNumber = UserToEdit.PhoneNumber;
    }
    return View(model);
}
HTTPPost UpdateUser Method:

To create the HTTPPost UpdateUser Method, follow these steps. Firstly, through an HTTP Post request, obtain the user’s information that needs to be updated. Secondly, obtain the user manager from the OWIN context by using the GetUserManager method. Thirdly, find the user to update by its id using the FindById method. Fourthly, update the user using the Update method. Lastly, check the Succeeded property of the IdentityResult object to verify whether the operation was successful. If the operation was unsuccessful, use the AddModelError method to add the Errors to the ModelState by looping through the list of errors.

[HttpPost]
public ActionResult UpdateUser(EditUserViewModel model)
{
    if (ModelState.IsValid)
    {
        //Create an instance of ApplicationUserManager class as we want to fetch the user details
        ApplicationUserManager UserManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();

        //Fetch the User Details by UserId using the FindById method
        ApplicationUser UserToEdit = UserManager.FindById(model.UserId);

        if (UserToEdit.UserName != model.UserName)
            UserToEdit.UserName = model.UserName;

        if (UserToEdit.FirstName != model.FirstName)
            UserToEdit.FirstName = model.FirstName;

        if (UserToEdit.LastName != model.LastName)
            UserToEdit.LastName = model.LastName;

        if (UserToEdit.Email != model.Email)
            UserToEdit.Email = model.Email;

        if (UserToEdit.PhoneNumber != model.PhoneNumber)
            UserToEdit.PhoneNumber = model.PhoneNumber;

        //Call the Update method to Update the User data
        IdentityResult result = UserManager.Update(UserToEdit);
        if (result.Succeeded)
        {
            return RedirectToAction("Index", "Home");
        }

        foreach (string error in result.Errors)
            ModelState.AddModelError("", error);
    }

    return View(model);
}
Modifying Login HTTPPost Method of Account Controller

By default, whenever you try to log in by clicking on the Login button, it will not work. So, let us modify the Login HTTPPost method of the Account Controller as follows. Here, we first find the user by using the Email and then we call the PasswordSignInAsync method. With these changes, your login functionality is going to work.

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }

    var user = UserManager.FindByEmail(model.Email);
    var result = await SignInManager.PasswordSignInAsync(user.UserName, model.Password, model.RememberMe, shouldLockout: false);

    // This doesn't count login failures towards account lockout
    // To enable password failures to trigger account lockout, change to shouldLockout: true
    // var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: true);
    switch (result)
    {
        case SignInStatus.Success:
            return RedirectToLocal(returnUrl);
        case SignInStatus.LockedOut:
            return View("Lockout");
        case SignInStatus.RequiresVerification:
            return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
        case SignInStatus.Failure:
        default:
            ModelState.AddModelError("", "Invalid login attempt.");
            return View(model);
    }
}
Adding UpdateUser.cshtml view:

Next, add a view with the name UpdateUser.cshtml within the Home folder which is inside the View Folder. Once you add the UpdateUser.cshtml view, then copy and paste the following code into it.

@model AspNetIdentityWithNewProject.Models.EditUserViewModel

@{
    ViewBag.Title = "UpdateUser";
}

<h2>UpdateUser</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    
<div class="form-horizontal">
    
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    @Html.Hidden("UserId", @Model.UserId)
   
    <div class="form-group">
        @Html.LabelFor(model => model.UserName, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.UserName, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.UserName, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.PhoneNumber, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.PhoneNumber, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.PhoneNumber, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Update" class="btn btn-default" />
        </div>
    </div>
</div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>
Modifying _LoginPartial.cshtml View:

Next, we need to modify the _LoginPartial.cshtml View. So, open _LoginPartial.cshtml View which you can find inside the shared folder and then copy and paste the following code into it. So, basically, whenever the user login, we are showing the Update button.

@using Microsoft.AspNet.Identity
@if (Request.IsAuthenticated)
{
    using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
    {
        @Html.AntiForgeryToken()

        <ul class="nav navbar-nav navbar-right">
            <li>
                @Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
            </li>
            <li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
        </ul>
    }
    <ul class="nav navbar-nav navbar-right">
        <li>
            @Html.ActionLink("Update", "UpdateUser", "Home", routeValues: new { UserId = User.Identity.GetUserId() }, htmlAttributes: new { title = "Update" })
        </li>
    </ul>
}
else
{
    <ul class="nav navbar-nav navbar-right">
        <li>@Html.ActionLink("Register", "AddUser", "Home", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>
        <li>@Html.ActionLink("Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
    </ul>
}

With the above changes in place, now run the application. Then Login using your valid credentials and then click on the Update button in the Menu. Once you click on the Update button, then it will show you the following Update user screen. Modify the data as expected and then click on the Update button as shown in the below image.

How to Update and Delete a User Account in ASP.NET Identity

Once you click on the Update button, then you should see the updated data in the database. This is how you can update the user data in ASP.NET Identity using ASP.NET MVC Application.

Note: In addition to finding the user by the FindById method, we can also use the FindByName method or the FindByEmail method to find the user to update by its username or by its email address.

How to Delete a User in ASP.NET Identity:

The Delete Method of the ApplicationUserManager instance deletes the user passed as a parameter to the method and returns the result of the operation as an IdentityResult object as follows.

IdentityResult result = UserManager.Delete(UserToDelete);

IdentityResult result = await UserManager.DeleteAsync(UserToDelete);

The Delete method is called by the ApplicationUserManager instance which is responsible for performing the user-related operations. In this case, it is going to delete the user from the database. So, the following DeleteUser Method is going to delete an existing user from the database in ASP.NET Identity.

[HttpPost]
public ActionResult DeleteUser(string UserId)
{
    //Create an Instance of ApplicationUserManager who is responsible for doing user-related operations
    ApplicationUserManager UserManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();

    //Find the user to Delete by using FindById Method
    ApplicationUser UserToDelete = UserManager.FindById(UserId);

    //If the User Exists Then Delete the User
    if (UserToDelete != null)
    {
        //Delete the User by using Delete method of ApplicationUserManager Insance
        IdentityResult result = UserManager.Delete(UserToDelete);
        if (result.Succeeded)
        {
            return RedirectToAction("Index", "Home");
        }

        foreach (string error in result.Errors)
            ModelState.AddModelError("", error);

        return View(UserId);
    }

    return HttpNotFound();
}

The code above retrieves the UserId of the user that needs to be deleted through an HTTP Post request. We obtain the user manager from the OWIN context by calling the GetUserManager method and then utilize the FindById method to locate the user by their id for deletion. If the user is not found, we display an HTTP 404 error page. However, if the user is found, we delete them and verify the success of the operation by accessing the Succeeded property of the IdentityResult object. In case of failure, we utilize the AddModelError method to add any errors in the list to the ModelState object.

In the next article, I am going to discuss How to Update a User Password in ASP.NET Identity. Here, in this article, I try to explain How to Update and Delete a User Account in ASP.NET Identity. I hope you enjoy this Update and Delete User Account in ASP.NET Identity article.

Leave a Reply

Your email address will not be published. Required fields are marked *