Before proceeding to this article please go to Assigning Role to User in ASP.NET MVC Membership.
Here we will learn how to assign roles to the users in ASP.NET membership provider. For assigning the roles to the user we need to add a model for member list and roles List.
First add a model class in account model.cs class name is “AssignRolesToUsers”.
- public class AssignRole
- {
- [Required(ErrorMessage = " Select proper UserRole Name")]
- public string UserRoleName
- {
- get;
- set;
- }
- [Required(ErrorMessage = "Select UserName")]
- public string UserID
- {
- get;
- set;
- }
- public List < SelectListItem > Userlist
- {
- get;
- set;
- }
- public List < SelectListItem > UserRolesList
- {
- get;
- set;
- }
- }
- [HttpGet]
- public ActionResult AssignRolesToUsers()
- {
- }
- public class UsersRoleContext: DbContext
- {
- public UsersRoleContext(): base("DBConnectionForMembership")
- {}
- public DbSet < Role > UserRoles
- {
- get;
- set;
- }
- public DbSet < UserProfile > UserProfile
- {
- get;
- set;
- }
- }
So for that write the following code:
- [NonAction]
- public List < SelectListItem > GetAll_UserRoles()
- {
- List < SelectListItem > listrole = new List < SelectListItem > ();
- listrole.Add(new SelectListItem
- {
- Text = "select", Value = "0"
- });
- using(UsersRoleContext db = new UsersRoleContext())
- {
- foreach(var item in db.UserRoles)
- {
- listrole.Add(new SelectListItem
- {
- Text = item.RoleName, Value = Convert.ToString(item.RoleId)
- });
- }
- }
- return listrole;
- }
- [NonAction]
- public List < SelectListItem > GetAll_Users()
- {
- List < SelectListItem > listuser = new List < SelectListItem > ();
- listuser.Add(new SelectListItem
- {
- Text = "Select", Value = "0"
- });
- using(UsersRoleContext db = new UsersRoleContext())
- {
- foreach(var item in db.UserProfile)
- {
- listuser.Add(new SelectListItem
- {
- Text = item.UserName, Value = Convert.ToString(item.UserId)
- });
- }
- }
- return listuser;
- }
- [HttpGet]
- public ActionResult AssignRolesToUsers()
- {
- AssignRole _addignroles = new AssignRole();
- _addignroles.UserRolesList = GetAll_UserRoles();
- _addignroles.Userlist = GetAll_Users();
- return View(_addignroles);
- }

After clicking on add it will generate some code for us but we need to make changes in this view:
- @model MvcMembershipProvider.Models.AssignRole
- @{
- ViewBag.Title = "AssignRolesToUsers";
- }
- <h2>AssignRolesToUsers</h2>
- <link href="~/bootstrap/css/bootstrap.min.css" rel="stylesheet" />
- <script src="~/bootstrap/js/bootstrap.min.js"></script>
- @using (Html.BeginForm())
- {
- @Html.AntiForgeryToken()
- @Html.ValidationSummary(true)
- <fieldset>
- <legend>AssignRole</legend>
- <div class="editor-label">
- @Html.LabelFor(model => model.UserRoleName)
- </div>
- <div class="editor-field">
- @*@Html.EditorFor(model => model.UserRoleName)*@
- @Html.DropDownListFor(m => m.UserRoleName, newSelectList(Model.UserRolesList, "Value", "Text"),
- new { style = "width:200px", @class = "form-control" })
- @Html.ValidationMessageFor(model => model.UserRoleName)
- </div>
- <div class="editor-label">
- @Html.LabelFor(model => model.UserID)
- </div>
- <div class="editor-field">
- @*@Html.EditorFor(model => model.UserID)*@
- @Html.DropDownListFor(m => m.UserID, new SelectList(Model.Userlist, "Value","Text"),
- new { style = "width:200px", @class = "form-control" })
- @Html.ValidationMessageFor(model => model.UserID)
- </div>
- <p>
- <input type="submit" value="Create" />
- </p>
- </fieldset>
- }
- <div>
- @Html.ActionLink("Back to List", "Index")
- </div>
- @section Scripts {
- @Scripts.Render("~/bundles/jqueryval")
- }
http://localhost:50526/Account/AssignRolesToUsers

Add role to the user
Now here we will create action method to add the role to the users with the post method.
Write the following code in Post action method for the “AssignRolesToUsers”.
- [HttpPost]
- [ValidateAntiForgeryToken]
- public ActionResult AssignRolesToUsers(AssignRole _assignRole)
- {
- if (_assignRole.UserRoleName == "0")
- {
- ModelState.AddModelError("RoleName", " select UserRoleName");
- }
- if (_assignRole.UserID == "0")
- {
- ModelState.AddModelError("UserName", " select Username");
- }
- if (ModelState.IsValid)
- {
- if (Get_CheckUserRoles(Convert.ToInt32(_assignRole.UserID)) == true)
- {
- ViewBag.ResultMessage = "Current user is already has the role";
- }
- else
- {
- var UserName = GetUserName_BY_UserID(Convert.ToInt32(_assignRole.UserID));
- var UserRoleName = GetRoleNameByRoleID(Convert.ToInt32(_assignRole.UserRoleName));
- Roles.AddUserToRole(UserName, UserRoleName);
- ViewBag.ResultMessage = "Username added to role successfully !";
- }
- _assignRole.UserRolesList = GetAll_UserRoles();
- _assignRole.Userlist = GetAll_Users();
- return View(_assignRole);
- }
- else
- {
- _assignRole.UserRolesList = GetAll_UserRoles();
- _assignRole.Userlist = GetAll_Users();
- }
- return View(_assignRole);
- }
- public string GetUserName_BY_UserID(int UserId)
- {
- using(UsersRoleContext context = new UsersRoleContext())
- {
- var UserName = (from UP in context.UserProfile where UP.UserId == UserId select UP.UserName).SingleOrDefault();
- return UserName;
- }
- }
- public string GetRoleNameByRoleID(int RoleId)
- {
- using(UsersRoleContext context = new UsersRoleContext())
- {
- var roleName = (from UP in context.UserRoles where UP.RoleId == RoleId select UP.RoleName).SingleOrDefault();
- return roleName;
- }
- }
- public bool Get_CheckUserRoles(int UserId)
- {
- using(UsersRoleContext context = new UsersRoleContext())
- {
- var data = (from WR in context.webpages_UsersInRole join R in context.UserRoles on WR.RoleId equals R.RoleId where WR.UserId == UserId orderby R.RoleId select new
- {
- WR.UserId
- }).Count();
- if (data > 0)
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- }
http://localhost:50526/Account/AssignRolesToUsers

Database table is:

Create a view with all roles and all the users.
First for this add a model in account.cs class under model folder. So code for this is:
- public class AllroleWithAllUser
- {
- public string UserRoleName { get; set; }
- public string UserName { get; set; }
- public IEnumerable<AllroleWithAllUser> AllDetailsUserlist { get; set; }
- }
- [NonAction]
- public List < AllroleWithAllUser > GetUserNameResepectiveToRole()
- {
- using(UsersRoleContext db = new UsersRoleContext())
- {
- var Alldata = (from User in db.UserProfile join WU in db.webpages_UsersInRole on User.UserId equalsWU.UserId join WR in db.UserRoles on WU.RoleId equals WR.RoleId select new AllroleWithAllUser
- {
- UserName = User.UserName, UserRoleName = WR.RoleName
- }).ToList();
- return Alldata;
- }
- }
- [HttpGet]
- public ActionResult DisplayAllUserroles()
- {
- AllroleWithAllUser _alluserWithRole = new AllroleWithAllUser();
- _alluserWithRole.AllDetailsUserlist = GetUserNameResepectiveToRole();
- return View(_alluserWithRole);
- }

And the write following code in the view:
- @model MvcMembershipProvider.Models.AllroleWithAllUser
- @using GridMvc.Html
- @{
- ViewBag.Title = "DisplayAllUserroles";
- }
- <h2>DisplayAllUserroles</h2>
- <link href="~/Content/Gridmvc.css" rel="stylesheet" />
- <link href="~/bootstrap/css/bootstrap.min.css" rel="stylesheet" />
- <script src="~/Scripts/jquery-1.9.1.min.js"></script>
- <script src="~/Scripts/gridmvc.js"></script>
- @Html.Grid(Model.AllDetailsUserlist).Columns(columns =>
- {
- columns.Add(c => c.UserName).Titled("UserName").Filterable(true).SetWidth(300);
- columns.Add(c => c.UserRoleName).Titled("RoleName").Filterable(true).SetWidth(300);
- }).WithPaging(10).Sortable(true)
http://localhost:50526/Account/DisplayRoleForUsers


Ali HameedPosted Apr 19, 2017, 3:23 AM
Where is the UsersInRoles Model Class defined?
Munesh SharmaPosted May 25, 2016, 8:31 AM
thank you all
Vignesh ManiPosted May 25, 2016, 8:28 AM
Nice
Thiruppathi RPosted May 25, 2016, 4:35 AM
Nice one..
Gowtham RajamanickamPosted May 25, 2016, 1:15 AM
Good one..
Munesh SharmaPosted May 25, 2016, 12:22 AM
thank you all
Debasis SahaPosted May 24, 2016, 1:48 PM
Good One..
Kuppurasu NagarajPosted May 24, 2016, 12:05 PM
Nice Sharing..