Using Membership in ASP.Net MVC 4

It is best to use ready-made membership rather than creating an entirely new one for every application we create.

Let's start creating a MVC application first.

Creating MVC application

In Visual Studio select "File" -> "New" -> "Project...". A new wizard will be shown. Inside that select Visual C# Template and inside that Web and from the list of templates select ASP.NET MVC 4 Web Application then provide name for the project “MembershipDEMO”.




Then in the Project Templates select the Basic template.



After selecting Basic template then click on the OK button.

We have created a new project.



Adding Reference

Now we need to add a reference of WebMatrix.Data and WebMatrix.WebData.

For adding the reference right-click on References then select Add Reference.

WebMatrix.Data 2.0.0.0

WebMatrix.Data 2.0.0.0



After selecting just click on the OK button.

Then you will find the references have been add to your references folder.



Creating Database

Now create database in SQL Server with any name but I am naming it “UserDb” .



After creating the database now let's add the connection string.

Adding ConnectionString

Add the connection string in the Web.config file as in the following:
  1. <connectionStrings>  
  2.    <add name="DBConnection"  
  3.   connectionString="Data Source=saipc;Database=UserDb;UID=sa;Password=Pass$123"    providerName=   "System.Data.SqlClient" />  
  4. </connectionStrings>  
After adding the connection string now let's add Membership tables to the Userdb database.

For that we just need to add a line in Global.asax as in the following:
  1. WebSecurity.InitializeDatabaseConnection("DBConnection""Users""Id""UserName", autoCreateTables:true);  
After Ad3ding the Initialize Data3base Conne3ction now just run your application.

After running the application it will create all membership tables in the Userdb database.



Now we have tables with us that can store User Details and Roles. Now we need to create a UI for taking input from users.

Now we need to display data and get input. For that we need to create a Model first.

Adding Models

We will create 4 Models as in the following:
  1. AssignRoleVM
  2. Login
  3. Register
  4. Role

AssignRoleVM Model

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel.DataAnnotations;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7.   
  8. namespace MembershipDEMO.Models  
  9. {  
  10.     public class AssignRoleVM  
  11.     {  
  12.           
  13.             [Required(ErrorMessage = "Enter Role Name")]  
  14.             public string RoleName { getset; }  
  15.             [Required(ErrorMessage = "Enter User name")]  
  16.             public string UserName { getset; }  
  17.             public List<SelectListItem> Userlist { getset; }  
  18.             public List<SelectListItem> RolesList { getset; }  
  19.      }  
  20.   
  21.         public class AllroleandUser  
  22.         {  
  23.             public string RoleName { getset; }  
  24.             public string UserName { getset; }  
  25.   
  26.             public List<AllroleandUser> AllDetailsUserlist { getset; }  
  27.         }  
  28.       
  29. }  
Login Model
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel.DataAnnotations;  
  4. using System.Linq;  
  5. using System.Web;  
  6.   
  7. namespace MembershipDEMO.Models  
  8. {  
  9.     public class Login  
  10.     {  
  11.         [Required]  
  12.         [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]  
  13.         [DataType(DataType.Password)]  
  14.         [Display(Name = "Password")]  
  15.         public string password { getset; }  
  16.   
  17.         [Required(ErrorMessage = "Enter User name")]  
  18.         public string username { getset; }  
  19.     }  
  20. }  
Register Model
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel.DataAnnotations;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7.   
  8. namespace MembershipDEMO.Models  
  9. {  
  10.     public class Register  
  11.     {  
  12.         [Required(ErrorMessage = "Enter Full Name")]  
  13.   
  14.         public string FullName { getset; }  
  15.         [Required(ErrorMessage = "Enter User name")]  
  16.   
  17.         public string username { getset; }  
  18.         [Required(ErrorMessage = "Enter EmailID")]  
  19.   
  20.         public string EmailID { getset; }  
  21.   
  22.         [Required]  
  23.         [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]  
  24.         [DataType(DataType.Password)]  
  25.         [Display(Name = "Password")]  
  26.   
  27.         public string password { getset; }  
  28.   
  29.   
  30.         [DataType(DataType.Password)]  
  31.         [Display(Name = "Confirm password")]  
  32.         [Compare("password", ErrorMessage = "The password and confirmation password do not match.")]  
  33.         public string Confirmpassword { getset; }  
  34.     }  
  35. }  
Role Model
  1. public class Role  
  2. {  
  3.      [Required(ErrorMessage = "Enter Role name")]  
  4.      [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]  
  5.      public string RoleName { getset; }  
  6. }  
Now we have added the Model.

Adding Dapper Reference.

Now we will add a Dapper reference to the project because we need to get data from the database.

Its simple and easy to use.

For adding, just right-click on the project and select Manage Nuggets Package.
 


In the Search box type Dapper.

Inside this select Dapper dot net.

Created by: Sam Saffron, Marc Gravell.
 
 

Click on Install.



Now we have added Dapper. Let's move towards adding the Controllers.

Adding AccountController

First we will add an Account Controller.





The following is the code snippet of AccountController:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using MembershipDEMO.Models;  
  7. using WebMatrix.WebData;  
  8.   
  9. namespace MembershipDEMO.Controllers  
  10. {  
  11.     public class AccountController : Controller  
  12.     {  
  13.          
  14.         [HttpGet]  
  15.         public ActionResult Login()  
  16.         {  
  17.             return View();  
  18.         }  
  19.     }  
  20. }  
After adding the Controller now let's add a View to this Login Action Method.

Adding View (Login)

For adding the View just right-click inside the Action Method Login and select Add View. When you select Add View a new wizard will be shown. Inside this we will select Model class Login and Scaffolding as Create and finally click on the Add button.



Now save and run the application.

Displaying Error after running

You get the following error. Then you need to add some lines in Web.config:



Adding Membership related tags in Web.config

In Web.config under System.web:

  1. <membership defaultProvider="SimpleMembershipProvider">  
  2.   <providers>  
  3.     <clear />  
  4.     <add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />  
  5.   </providers>  
  6. </membership>  
  7. <roleManager enabled="true" defaultProvider="SimpleRoleProvider">  
  8.   <providers>  
  9.     <clear />  
  10.     <add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData" />  
  11.   </providers>  
  12. </roleManager>  
Change Properties of Assembly for WebMatrix.Data and WebMatrix.WebData

Then you need to change the properties of the WebMatrix.Data and WebMatrix.WebData references.

Right-click on WebMatrix.Data and select Properties.



In properties change Copy Local to true.



You need to repeat that for WebMatrix.WebData.



Now run the application again.

Accessing Login page



Now we can see that we have the Login View. Now let's create its Login Post Method.

Code snippet for Login Action Method (Post)

In this method we will use a Login Model as input and then we are passing it to WebSecurity. Login to check that the Username and Password have been entered and is valid. If it is valid then we will redirect it to the Dashboard else to the same Login page.

  1. [HttpPost]  
  2. public ActionResult Login(Login login)  
  3. {  
  4.     if (ModelState.IsValid)  
  5.     {  
  6.         bool success = WebSecurity.Login(login.username, login.password, false);  
  7.         if (success)  
  8.         {  
  9.             string returnUrl = Request.QueryString["ReturnUrl"];  
  10.             if (returnUrl == null)  
  11.             {  
  12.                 Response.Redirect("~/Home/index");  
  13.             }  
  14.             else  
  15.             {  
  16.                 Response.Redirect(returnUrl);  
  17.             }  
  18.         }  
  19.     }  
  20.     else  
  21.     {  
  22.         ModelState.AddModelError("Error""Please enter Username and Password");  
  23.     }  
  24.     return View(login);  
  25.   
  26. }    
We have completed the Login part. Now let's move to the registration.

Adding Register Action Method

Now add another Action Method with the name Register.
  1. [HttpGet]  
  2. public ActionResult Register()  
  3. {  
  4.     return View();  
  5.  }  
Adding View for Register Action Method

For adding the View just right-click inside Action Method Register and select Add View. When you select Add View a new wizard will be shown. Inside this we will select Model class Register and Scaffolding as Create and finally click on the Add button.



After creating Register View now just run the application and check.

Now run the application again.

Accessing Register page



Now we can see that we have a Register View. Now let's create the Register Post Method.

Code snippet for Register Action Method (Post)

In this Action Method we will use the Register Model as input and using the built-in method of Membership WebSecurity.CreateUserAndAccount we will pass the Register Model to it and then redirect to the Login page.
  1. [HttpPost]  
  2. public ActionResult Register(Register register)  
  3. {  
  4.     if (ModelState.IsValid)  
  5.     {  
  6.         if (!WebSecurity.UserExists(register.username))  
  7.         {  
  8.             WebSecurity.CreateUserAndAccount(register.username, register.password,  
  9.                 new { FullName = register.FullName, EmailID = register.EmailID });  
  10.             Response.Redirect("~/account/login");  
  11.         }  
  12.     }  
  13.     else  
  14.     {  
  15.         ModelState.AddModelError("Error""Please enter all details");  
  16.     }  
  17.     return View();  
  18.  }  
Until now we have added 4 Action Methods as in the following:



Now let's move to adding a Role.

Adding RoleCreate ActionMethod

The following adds the Action Method RoleCreate.
  1. [HttpGet]  
  2. public ActionResult RoleCreate()  
  3. {  
  4.     return View();  
  5.  }   

Adding View for RoleCreate Action Method



After creating the Role View now just run the application and check.

Now run the application again.

Accessing RoleCreate page



Now we can see that we have the Role View. Now let's create the Role Post Method.

Code snippet for RoleCreate Action Method (Post)

In this Action Method we will use a Role Model as input and then validate the Role using the Roles.RoleExists method to check whether or not the role name is already created. If yes then we will show an error Message else we will create the Role.
  1. [HttpPost]  
  2.  public ActionResult RoleCreate(Role role)  
  3.  {  
  4.      if (ModelState.IsValid)  
  5.      {  
  6.          if (Roles.RoleExists(role.RoleName))  
  7.          {  
  8.              ModelState.AddModelError("Error""Rolename already exists");  
  9.              return View(role);  
  10.          }  
  11.          else  
  12.          {  
  13.              Roles.CreateRole(role.RoleName);  
  14.              return RedirectToAction("RoleIndex""Account");  
  15.          }  
  16.      }  
  17.      else  
  18.      {  
  19.          ModelState.AddModelError("Error""Please enter Username and Password");  
  20.      }  
  21.      return View(role);  
  22. }  
Now let's proceed to add RoleAddToUser.

Adding RoleAddToUser ActionMethod

In this Action Method we will fill 2 Dropdownlists, 1) Roles list 2) User list.

  1. [HttpGet]  
  2. public ActionResult RoleAddToUser()  
  3. {  
  4.     AssignRoleVM objvm = new AssignRoleVM();  
  5.   
  6.     List<SelectListItem> listrole = new List<SelectListItem>(); //list 1  
  7.   
  8.     listrole.Add(new SelectListItem { Text = "Select", Value = "0" });  
  9.   
  10.     foreach (var item in Roles.GetAllRoles())  
  11.     {  
  12.         listrole.Add(new SelectListItem { Text = item, Value = item });  
  13.     }  
  14.   
  15.     objvm.RolesList = listrole;  
  16.   
  17.     using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Mystring"].ToString()))  
  18.     {  
  19.         var Userlist = con.Query("SELECT * FROM Users").ToList();  
  20.   
  21.         List<SelectListItem> listuser = new List<SelectListItem>(); //list 2  
  22.   
  23.         listuser.Add(new SelectListItem { Text = "Select", Value = "0" });  
  24.   
  25.         foreach (var item in Userlist)  
  26.         {  
  27.             listuser.Add(new SelectListItem { Text = item.UserName, Value = item.UserName });  
  28.         }  
  29.   
  30.         objvm.Userlist = listuser;  
  31.     }  
  32.   
  33.     return View(objvm);  
  34. }  
We need to fill in the first Dropdownlist that is of Role.
  1. List<SelectListItem> listrole = new List<SelectListItem>(); //list 1  
  2. listrole.Add(new SelectListItem { Text = "Select", Value = "0" });  
  3. foreach (var item in Roles.GetAllRoles())  
  4. {  
  5.     listrole.Add(new SelectListItem { Text = item, Value = item });  
  6. }  
  7. objvm.RolesList = listrole;  
We need to fill in the second Dropdownlist that is of User.
  1. using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBconnection"].ToString()))  
  2. {  
  3.       var Userlist = con.Query("SELECT * FROM Users").ToList();  
  4.   
  5.       List<SelectListItem> listuser = new List<SelectListItem>(); //list 2  
  6.   
  7.       listuser.Add(new SelectListItem { Text = "Select", Value = "0" });  
  8.   
  9.       foreach (var item in Userlist)  
  10.       {  
  11.           listuser.Add(new SelectListItem { Text = item.UserName, Value = item.UserName });  
  12.       }  
  13.   
  14.       objvm.Userlist = listuser;  
  15. }  
Adding View for RoleAddToUser Action Method

For adding the View just right-click inside the Action Method RoleAddToUser and select Add View. When you select Add View a new wizard will be shown. Inside this we will select the Model class AssignRoleVM and Scaffolding as Create and finally click on the Add button.



After adding the View we need to change some code in the view by adding 2 dropdownlists to it.

After creating the RoleAddToUser View now just run the application and check.

Now run the application again.

Accessing RoleAddToUser page



Now we can see that we have the RoleAddToUser View. Now let's create its RoleAddToUser Post method.

Code snippet for RoleAddToUser Action Method (Post)

If you see, this action method is quite large.

Inside this we are first validating that the role and user dropdownlist is selected or not. If not then we will add the Model Error for it.

Then Validating that the role is already assigned to the user, if yes then add the Model Error else we will assign the Role to the user.

After adding we need to refill your Dropdownlist. For that we are re-populating it from the database.

Finally returning Model.
  1. [HttpPost]  
  2. [ValidateAntiForgeryToken]  
  3. public ActionResult RoleAddToUser(AssignRoleVM objvm)  
  4. {  
  5.   
  6.     if (objvm.RoleName == "0")  
  7.     {  
  8.         ModelState.AddModelError("RoleName""Please select RoleName");  
  9.     }  
  10.   
  11.     if (objvm.UserName == "0")  
  12.     {  
  13.         ModelState.AddModelError("UserName""Please select Username");  
  14.     }  
  15.   
  16.     if (ModelState.IsValid)  
  17.     {  
  18.   
  19.         if (Roles.IsUserInRole(objvm.UserName, objvm.RoleName))  
  20.         {  
  21.             ViewBag.ResultMessage = "This user already has the role specified !";  
  22.         }  
  23.         else  
  24.         {  
  25.             Roles.AddUserToRole(objvm.UserName, objvm.RoleName);  
  26.   
  27.             ViewBag.ResultMessage = "Username added to the role successfully !";  
  28.         }  
  29.   
  30.   
  31.         List<SelectListItem> lirole = new List<SelectListItem>();  
  32.         lirole.Add(new SelectListItem { Text = "Select", Value = "0" });  
  33.   
  34.         foreach (var item in Roles.GetAllRoles())  
  35.         {  
  36.             lirole.Add(new SelectListItem { Text = item, Value = item });  
  37.         }  
  38.   
  39.         objvm.RolesList = lirole;  
  40.   
  41.         using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ToString()))  
  42.         {  
  43.             var Userlist = con.Query("SELECT * FROM Users").ToList();  
  44.             List<SelectListItem> listuser = new List<SelectListItem>();  
  45.             listuser.Add(new SelectListItem { Text = "Select", Value = "0" });  
  46.   
  47.             foreach (var item in Userlist)  
  48.             {  
  49.                 listuser.Add(new SelectListItem { Text = item.UserName, Value = item.UserName });  
  50.             }  
  51.             objvm.Userlist = listuser;  
  52.         }  
  53.   
  54.         return View(objvm);  
  55.   
  56.     }  
  57.   
  58.     else  
  59.     {  
  60.         List<SelectListItem> lirole = new List<SelectListItem>();  
  61.         lirole.Add(new SelectListItem { Text = "Select", Value = "0" });  
  62.   
  63.         foreach (var item in Roles.GetAllRoles())  
  64.         {  
  65.             lirole.Add(new SelectListItem { Text = item, Value = item });  
  66.         }  
  67.   
  68.         objvm.RolesList = lirole;  
  69.   
  70.         using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ToString()))  
  71.         {  
  72.             var Userlist = con.Query("SELECT * FROM Users").ToList();  
  73.             List<SelectListItem> listuser = new List<SelectListItem>();  
  74.             listuser.Add(new SelectListItem { Text = "Select", Value = "0" });  
  75.   
  76.             foreach (var item in Userlist)  
  77.             {  
  78.                 listuser.Add(new SelectListItem { Text = item.UserName, Value = item.UserName });  
  79.             }  
  80.   
  81.             objvm.Userlist = listuser;  
  82.         }  
  83.         ModelState.AddModelError("Error""Please enter Username and Password");  
  84.     }  
  85.     return View(objvm);  
  86. }  
Now let's procced to add DeleteRoleForUser.

Adding DeleteRoleForUser ActionMethod

In this action method I will delete the role for the User. For that I have 2 dropdownlists as in the following:
  1. Roles list 
  2. User list
  1. [HttpGet]  
  2. public ActionResult DeleteRoleForUser()  
  3. {  
  4.     AssignRoleVM objvm = new AssignRoleVM();  
  5.   
  6.     List<SelectListItem> lirole = new List<SelectListItem>();  
  7.     lirole.Add(new SelectListItem { Text = "Select", Value = "0" });  
  8.   
  9.     foreach (var item in Roles.GetAllRoles())  
  10.     {  
  11.         lirole.Add(new SelectListItem { Text = item, Value = item });  
  12.     }  
  13.   
  14.     objvm.RolesList = lirole;  
  15.   
  16.     using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Mystring"].ToString()))  
  17.     {  
  18.         var Userlist = con.Query("SELECT * FROM Users").ToList();  
  19.   
  20.         List<SelectListItem> listuser = new List<SelectListItem>();  
  21.   
  22.         listuser.Add(new SelectListItem { Text = "Select", Value = "0" });  
  23.   
  24.         foreach (var item in Userlist)  
  25.         {  
  26.             listuser.Add(new SelectListItem { Text = item.UserName, Value = item.UserName });  
  27.         }  
  28.   
  29.         objvm.Userlist = listuser;  
  30.     }  
  31.   
  32.     return View(objvm);  
  33. }
Adding View for DeleteRoleForUser Action Method

For adding the View just right-click inside the Action Method DeleteRoleForUser and select Add View. When you select Add View a new wizard will be shown. Inside this we will select the Model class AssignRoleVM and Scaffolding as Empty and finally click on the Add button.



After adding the view just run application.

Accessing DeleteRoleForUser page



Code snippet for DeleteRoleForUser Action Method (Post)

Inside this Action Method we will check whether the Dropdownlist is selected or not. Then we check if this User is in a Role. If it is in a role then we will only delete it else we will add an Error Message for it.
  1. [HttpPost]  
  2. [ValidateAntiForgeryToken]  
  3. public ActionResult DeleteRoleForUser(AssignRoleVM objvm)  
  4. {  
  5.   
  6.     if (objvm.RoleName == "0")  
  7.     {  
  8.         ModelState.AddModelError("RoleName""Please select RoleName");  
  9.     }  
  10.   
  11.     if (objvm.UserName == "0")  
  12.     {  
  13.         ModelState.AddModelError("UserName""Please select Username");  
  14.     }  
  15.   
  16.     List<SelectListItem> lirole = new List<SelectListItem>();  
  17.     lirole.Add(new SelectListItem { Text = "Select", Value = "0" });  
  18.   
  19.     foreach (var item in Roles.GetAllRoles())  
  20.     {  
  21.         lirole.Add(new SelectListItem { Text = item, Value = item });  
  22.     }  
  23.   
  24.     objvm.RolesList = lirole;  
  25.   
  26.     using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ToString()))  
  27.     {  
  28.         var Userlist = con.Query("SELECT * FROM Users").ToList();  
  29.   
  30.         List<SelectListItem> listuser = new List<SelectListItem>();  
  31.   
  32.         listuser.Add(new SelectListItem { Text = "Select", Value = "0" });  
  33.   
  34.         foreach (var item in Userlist)  
  35.         {  
  36.             listuser.Add(new SelectListItem { Text = item.UserName, Value = item.UserName });  
  37.         }  
  38.   
  39.         objvm.Userlist = listuser;  
  40.     }  
  41.   
  42.     if (ModelState.IsValid)  
  43.     {  
  44.         if (Roles.IsUserInRole(objvm.UserName, objvm.RoleName))  
  45.         {  
  46.             Roles.RemoveUserFromRole(objvm.UserName, objvm.RoleName);  
  47.   
  48.             ViewBag.ResultMessage = "Role removed from this user successfully !";  
  49.         }  
  50.         else  
  51.         {  
  52.             ViewBag.ResultMessage = "This user doesn't belong to selected role.";  
  53.         }  
  54.     }  
  55.   
  56.     return View(objvm);  
  57. }  
After deleting the Roles for the User now let's proceed to delete the Role.

Adding another 2 Action Method RoleIndex and RoleDelete

For deleting roles I will use 2 Action Methods as in the following:
  1. for displaying roles RoleIndex
  2. for deleting roles that get role name as input
  1. public ActionResult RoleIndex()  
  2. {  
  3.     var roles = Roles.GetAllRoles();  
  4.     return View(roles);  
  5. }  
  6.   
  7. public ActionResult RoleDelete(string RoleName)  
  8. {  
  9.     Roles.DeleteRole(RoleName);  
  10.     return RedirectToAction("RoleIndex""Account");  
  11.  }  
Adding View for RoleIndex Action Method



After adding the view now just run the application.

Accessing RoleIndex page



Now let's work with another Action Method RoleDelete.

Adding RoleDelete ActionMethod

When the user clicks on the Delete button it will call another method, RoleDelete, with Rolename as the input parameter.

When you click on delete it will ask for confirmation.

Accessing RoleDelete page



Now we have completed the deleting part of the role. Now let's move towards displaying all the lists of the User and roles.

Adding DisplayAllUserroles ActionMethod


Inside this action Method we will display all the Roles assigned to the user with their Username.

  1. [HttpGet]  
  2. public ActionResult DisplayAllUserroles()  
  3. {  
  4.     AllroleandUser objru = null;  
  5.     List<AllroleandUser> RUlist = new List<AllroleandUser>();  
  6.   
  7. ng (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Mystring"].ToString()))  
  8.     {  
  9.   
  10.         string Query = @"SELECT U.UserName,ro.RoleName FROM Users U   
  11.                         Left JOIN webpages_UsersInRoles WU on U.Id = WU.UserId   
  12.                         Left JOIN webpages_Roles ro on WU.RoleId = ro.RoleId";  
  13.   
  14.         var RoleandUserList = con.Query(Query).ToList();  
  15.   
  16.   
  17.         foreach (var item in RoleandUserList)  
  18.         {  
  19.             objru = new AllroleandUser();  
  20.   
  21.             if (item.RoleName == null)  
  22.             {  
  23.                 objru.RoleName = "Role not Assign";  
  24.             }  
  25.             else  
  26.             {  
  27.                 objru.RoleName = item.RoleName;  
  28.             }  
  29.   
  30.             objru.UserName = item.UserName;  
  31.   
  32.             RUlist.Add(objru);  
  33.         }  
  34.   
  35.         objru.AllDetailsUserlist = RUlist;  
  36.     }  
  37.     return View(objru);  
  38.   
  39. }  
Now first add the View for DisplayAllUserroles.

Adding View for DisplayAllUserroles Action Method



For that we are getting all the data from the database and adding to the list of (List<AllroleandUser>) and sending the Model to the View.

After adding the view now just run the application.

Accessing DisplayAllUserroles page



Finally we have a bunch of Views.



Adding Logoff ActionMethod
  1. public ActionResult LogOff()  
  2.  {  
  3.      WebSecurity.Logout();  
  4.      Response.Redirect("~/Account/Login");  
  5.      return View();  
  6.  }  
Now we need to create a Dashboard for displaying all this link of Roles.

Adding Controller Dashboard


Code snippet for DashboardController.

Then add a View Index by right-clicking inside the View with an Empty Model.
  1. namespace MembershipDEMO.Controllers  
  2. {  
  3.     public class DashboardController : Controller  
  4.     {  
  5.         [Authorize(Roles = "Admin")]  
  6.         public ActionResult Index()  
  7.         {  
  8.             return View();  
  9.         }  
  10.   
  11.     }  
  12. }  
Code snippet of Index ActionMethod of DashboardController

The following is the link that we have added to the Dashboard View:
  1. @{  
  2.     ViewBag.Title = "Index";  
  3. }  
  4.   
  5. <h2>Index</h2>  
  6.   
  7. <h3>Roles Management</h3>  
  8. <ol class="round">  
  9.     <li class="one">  
  10.         @Html.ActionLink("List of all roles""RoleIndex""Account")  
  11.     </li>  
  12.   
  13.     <li class="two">  
  14.         @Html.ActionLink("Assign Role To User""RoleAddToUser""Account")  
  15.     </li>  
  16.   
  17.     <li class="three">  
  18.         @Html.ActionLink("CreateRole""RoleCreate""Account")  
  19.     </li>  
  20.   
  21.     <li class="four">  
  22.         @Html.ActionLink("DeleteRole""DeleteRoleForUser""Account")  
  23.     </li>  
  24.   
  25.     <li class="five">  
  26.         @Html.ActionLink("List of all roles Assign to User""DisplayAllUserroles""Account")  
  27.     </li>  
  28. </ol>  
Accessing Index page of DashboardController



Finally we need to add the Home Controller and make it the landing page after login.

Adding Controller Home
 


Code snippet for HomeController.
  1. namespace MembershipDEMO.Controllers  
  2. {  
  3.     public class HomeController : Controller  
  4.     {  
  5.   
  6.         public ActionResult Index()  
  7.         {  
  8.             return View();  
  9.         }  
  10.   
  11.     }  
  12. }  
Adding View for Index Action Method



Finally the output of the Homepage with the Roles Management link on it.

Accessing Index page of HomeController



Tip: Restrict Action and Controller with Authorize Attribute.

If you want to restrict the user of a specific role to some Action method then add an Authorize Attribute to it with the Role Name you want to restrict.

For Example:
  1. [Authorize(Roles = "Admin")]  
Restrict Controller
  1. [Authorize(Roles = "Admin")]  
  2.  public class DashboardController : Controller  
  3.  {  
  4.       return View();      
  5.  }  
Restrict Action Method
  1. [Authorize(Roles = "Admin")]  
  2. public ActionResult Index()  
  3. {  
  4.     return View();   
  5. }  
Thanks for reading this article. I Hope you have gotten how to use membership in ASP.NET MVC 4.

I made it as simple as possible and tried to explain every bit of code. Implement it and add comments to this article.

Finally we have completed Membership in ASP.NET MVC 4.

Up Next
    Ebook Download
    View all
    Learn
    View all