ASP.NET MVC: Create Role with ASP.NET Identity

By FoxLearn 5/29/2017 9:10:16 PM   6.8K
Create Role (ApplicationRole, ApplicationRoleManager) with ASP.NET Identity MVC 5 using C#, Entity Framework Code First

Step 1: Open IdentityModels class, then add ApplicationRole class as below

public class ApplicationRole : IdentityRole
{
    public ApplicationRole() : base() { }
    public ApplicationRole(string roleName) : base(roleName) { }
}

Step 2: Open ApplicationRoleManager class, then add ApplicationRoleManager class as below

public class ApplicationRoleManager : RoleManager<ApplicationRole>
{
    public ApplicationRoleManager(IRoleStore<ApplicationRole, string> roleStore) : base(roleStore) { }
    public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
    {
        var applicationRoleManager = new ApplicationRoleManager(new RoleStore<ApplicationRole>(context.Get<ApplicationDbContext>()));
        return applicationRoleManager;
    }
}

Step 3: Create a RoleViewModel class to transfer data between view and controller

public class RoleViewModel
{
    public RoleViewModel() { }

    public RoleViewModel(ApplicationRole role)
    {
        Id = role.Id;
        Name = role.Name;
    }

    public string Id { get; set; }
    public string Name { get; set; }
}

Step 4: Create a RoleController as below

public class RoleController : Controller
{
    private ApplicationRoleManager _roleManager;

    public RoleController()
    {
    }

    public RoleController(ApplicationRoleManager roleManager)
    {
        RoleManager = roleManager;
    }

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

    // GET: Role
    public ActionResult Index()
    {
        List<RoleViewModel> list = new List<RoleViewModel>();
        foreach (var role in RoleManager.Roles)
            list.Add(new RoleViewModel(role));
        return View(list);
    }

    public ActionResult Create()
    {
        return View();
    }

    [HttpPost]
    public async Task<ActionResult> Create(RoleViewModel model)
    {
        var role = new ApplicationRole() { Name = model.Name };
        await RoleManager.CreateAsync(role);
        return RedirectToAction("Index");
    }

    public async Task<ActionResult> Edit(string id)
    {
        var role = await RoleManager.FindByIdAsync(id);
        return View(new RoleViewModel(role));
    }

    [HttpPost]
    public async Task<ActionResult> Edit(RoleViewModel model)
    {
        var role = new ApplicationRole() { Id = model.Id, Name = model.Name };
        await RoleManager.UpdateAsync(role);
        return RedirectToAction("Index");
    }

    public async Task<ActionResult> Details(string id)
    {
        var role = await RoleManager.FindByIdAsync(id);
        return View(new RoleViewModel(role));
    }

    public async Task<ActionResult> Delete(string id)
    {
        var role = await RoleManager.FindByIdAsync(id);
        return View(new RoleViewModel(role));
    }

    public async Task<ActionResult> DeleteConfirmed(string id)
    {
        var role = await RoleManager.FindByIdAsync(id);
        await RoleManager.DeleteAsync(role);
        return RedirectToAction("Index");
    }
}

Step 5: You can use MVC Razor Template to generate views

Index view

@model IEnumerable<MvcDemo.Models.RoleViewModel>
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th></th>
    </tr>
    @foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
            @Html.ActionLink("Details", "Details", new { id=item.Id }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.Id })
        </td>
    </tr>
}
</table>

Create view

@model MvcDemo.Models.RoleViewModel
@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()    
    <div class="form-horizontal">
        <h4>RoleViewModel</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}
<div>
    @Html.ActionLink("Back to List", "Index")
</div>

Edit view

@model MvcDemo.Models.RoleViewModel
@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()    
    <div class="form-horizontal">
        <h4>RoleViewModel</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.Id)
        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>
    </div>
}
<div>
    @Html.ActionLink("Back to List", "Index")
</div>

Delete view

@model MvcDemo.Models.RoleViewModel
@{
    ViewBag.Title = "Delete";
}

<h2>Delete</h2>

<h3>Are you sure you want to delete this?</h3>
<div>
    <h4>RoleViewModel</h4>
    <hr />
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.Name)
        </dt>
        <dd>
            @Html.DisplayFor(model => model.Name)
        </dd>
    </dl>
    @using (Html.BeginForm()) {
        @Html.AntiForgeryToken()
        <div class="form-actions no-color">
            <input type="submit" value="Delete" class="btn btn-default" /> |
            @Html.ActionLink("Back to List", "Index")
        </div>
    }
</div>

Details view

@model MvcDemo.Models.RoleViewModel
@{
    ViewBag.Title = "Details";
}

<h2>Details</h2>

<div>
    <h4>RoleViewModel</h4>
    <hr />
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.Name)
        </dt>
        <dd>
            @Html.DisplayFor(model => model.Name)
        </dd>
    </dl>
</div>
<p>
    @Html.ActionLink("Edit", "Edit", new { id = Model.Id }) |
    @Html.ActionLink("Back to List", "Index")
</p>

VIDEO TUTORIALS