Update a role in ASP.NET Identity

Introduction


In order to update an existing role in ASP.NET Identity, we use the Update method.

Update


The Update method updates the role passed as a parameter and returns the result of the operation as an IdentityResult object.

IdentityResult result = RoleManager.Update(role);

The Update method is called by the RoleManager, which is responsible for performing the role-related operations.

RoleManager


We use the Get method to get the ApplicationRoleManager from the OwinContext.

private ApplicationRoleManager _roleManager;
public ApplicationRoleManager RoleManager
{
    get
    {
        return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>(); 
    }

    private set
    {
        _roleManager = value;
    }
}

Check the Roles management section, for more information about the configuration of the RoleManager.

Example


[HttpPost]
public ActionResult UpdateRole(EditRoleViewModel model)
{
    if (ModelState.IsValid)
    {
        IdentityRole roleToEdit = RoleManager.FindById(model.RoleId);

        if (roleToEdit == null)
        {
            return HttpNotFound();
        }

        if (roleToEdit.Name != model.RoleName)
            roleToEdit.Name = model.RoleName;

        IdentityResult result = RoleManager.Update(roleToEdit);
        if (result.Succeeded)
        {
            return RedirectToAction("Index", "Home", new { Id = model.RoleId });
        }

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

    return View(model);
}

In the above example, we get the information of the role to update via an HTTP Post request. We use the FindById method to find the role to update by its id and then we use the Update method in order to update this role. We access the Succeeded property of the IdentityResult object to check if the opration was successful. If it is not the case, we loop through the list of Errors and we add them to the ModelState by using the AddModelError method.

The EditRoleViewModel object is the ViewModel that we are using in order to render and validate the UpdateRole view.

public class EditRoleViewModel
{
    [Required]
    public string RoleId { get; set; }

    [Display(Name = "Role name")]
    [Required]
    public string RoleName { get; set; }
}

Namespaces


In order to use the Get method, the Update method, the IdentityResult object, and the IdentityRole object, you have to include the following namespaces :

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;