Before proceeding to this tutorial please go to Display Roles for the users in Asp.Net MVC Membership
Here we will learn how to 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.
1st
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; }
}
|
After
creating the model we need to add a action method in controller class name is
“AssignRolesToUsers”.
[HttpGet]
public ActionResult AssignRolesToUsers()
{
}
|
Now add a
DbSet to the UserProfile class
public class UsersRoleContext : DbContext
{
public UsersRoleContext()
: base("DBConnectionForMembership")
{
}
public DbSet<Role> UserRoles { get; set; }
public DbSet< UserProfile > UserProfile { get; set; }
}
|
Now create
two nonAction method got getAllUsers
and GetAllUserRoles in Account
Controller.
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;
}
|
Now add the
following code to the “AssignRolesToUsers” action method
[HttpGet]
public ActionResult AssignRolesToUsers()
{
AssignRole _addignroles = new AssignRole();
_addignroles.UserRolesList =
GetAll_UserRoles();
_addignroles.Userlist =
GetAll_Users();
return View(_addignroles);
}
|
Now after
assign the object value need to add view for this action method so for that
right click on this action method and select strongly typed model as
“AssignRoles” and scaffold template as create.
After click
on add it will generate some code for us nut 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, new SelectList(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")
}
|
Now run
your application and go to following url then o/p will look like this
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);
}
|
Following
code for get UserName by using userid
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;
}
}
|
Following
code for get UserRoleName by using userRoleId
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;
}
}
|
Following
code for checking that current user have role name or not
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;
}
}
}
|
Now run
your application and go to the following URL and check the entries
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; }
}
|
Write a
nonAction method in controller to get all user with respective UserRole
[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 equals WU.UserId
join WR in db.UserRoles on WU.RoleId equals WR.RoleId
select new AllroleWithAllUser { UserName =
User.UserName, UserRoleName = WR.RoleName }).ToList();
return Alldata;
}
}
|
Now write a
action method for getting this
[HttpGet]
public ActionResult DisplayAllUserroles()
{
AllroleWithAllUser _alluserWithRole = new AllroleWithAllUser();
_alluserWithRole.AllDetailsUserlist = GetUserNameResepectiveToRole();
return View(_alluserWithRole);
}
|
Now we need
to add a view for showing All user with their
respective Role. So right click on action method and add a view with scaffold template
as empty.
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)
|
Now run
your application and go to following URL
http://localhost:50526/Account/DisplayRoleForUsers
|
Download this project from this link Downlaod
EmoticonEmoticon