Membership Role management in MVC 4

List of Membership role management like Create and delete role are explained in the article below.

The membership roles are available in webpages_Roles and webpages_UsersInRoles tables in the default connection. To use Roles add the following namespace in the page.

using System.Web.Security;

Create New Role

RoleExists receives role name as input and checks whether the username exists in webpages_Roles table. CreateRole method is used to create new role if its does not exists already in the webpages_Roles table. Add below code in “Role Controller”.

        [HttpGet]        
        public ActionResult RoleCreate()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult RoleCreate(string RoleName)
        {
            if (string.IsNullOrEmpty(RoleName))
            {
                ViewBag.ErrorMsg = "Role Name is required";
                ModelState.AddModelError("RoleName", ViewBag.ErrorMsg);
            }
            else if (Roles.RoleExists(RoleName))
            {
                ViewBag.ErrorMsg = "Role Name already exists";
                ModelState.AddModelError("RoleName", ViewBag.ErrorMsg);
            }
            if (ModelState.IsValid)
            {
                Roles.CreateRole(Request.Form["RoleName"]);
                return RedirectToAction("RoleIndex", "Role");
            }
            else
            {
                return View();
            }
        }

Create Role View

@{
    ViewBag.Title = "Manage Role";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div class="spacerBody">
    <p>&nbsp;</p>
    @Html.ActionLink("Roles", "RoleIndex") | @Html.ActionLink("Manage Users Role", "RoleAddToUser")
</div>
<h2>Create Role</h2>
<br />
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <div>
        Enter Role name
    </div>
    <p>
        @Html.TextBox("RoleName")
        @if (ViewBag.ErrorMsg != null)
        {
            @Html.ValidationMessage("RoleName", (string)ViewBag.ErrorMsg)
        }
    </p>
    <input type="submit" value="Save" />
}

Delete Role

The code below should be added in Role controller and is used to get list of all the roles which has been created so far. GetAllRoles method is used to perform that action.

public ActionResult RoleIndex()
 {
     var roles = Roles.GetAllRoles();
     return View(roles);
 }

In the above code right click RoleIndex() and click on Add view to add a new view to RoleIndex. Add below code in the newly created view.

@{
    ViewBag.Title = "RoleIndex";
}
<link rel="stylesheet" type="text/css" href="~/Content/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="~/Content/bootstrap.min.js"></script>
<script src="~/Scripts/bootbox.min.js"></script>
<script type="text/javascript">

    function Deleteclick(pRoleName) {
        bootbox.confirm({
            message: "Are you sure you want to delete this?",
            buttons: {
                confirm: {
                    label: 'Ok',
                    className: 'btn-success'

                },
            },
            callback: function (result) {
                if (result) {
                    $.post('/Role/CheckuserinRole/', { RoleName: pRoleName }, function (data) {
                        if (data == true) {
                            $.post('/Role/DeleteRole/', { RoleName: pRoleName }, function (success) {
                                if (success) {
                                    window.location = '/Role/RoleIndex';
                                }
                            });

                        }
                        else {
                            bootbox.alert("The role " + pRoleName + " cannot be deleted because there are still users in the role");
                        }
                    });
                }
            }
        });
    }

</script>
<div class="spacerBody">
    <p>&nbsp;</p>
    @Html.ActionLink("Create New Role", "RoleCreate") | @Html.ActionLink("Manage Users Role", "RoleAddToUser") | @Html.ActionLink("Manage Users", "RemoveUser")
</div>
<h2>Roles</h2>
<div class="table">
    <table>
        @foreach (string Role in Model)
        {
            <tr>
                <td>@Role</td>
                <td><span onclick="Deleteclick('@Role');">
                    <a class="delLink">
                        <img src="/images/bullet.png" alt="Delete" class="imgBorder0" />
                        Delete</a>
                </span></td>
            </tr>
        }
    </table>
</div>

DeleteRole() is used to delete roles created in membership. Add below code in “Role Controller”.

[HttpPost]
public JsonResult DeleteRole(string RoleName)
{
    var roles = Roles.DeleteRole(RoleName);
    return Json(true, JsonRequestBehavior.AllowGet);
}