Simple Login Application using Sessions in ASP.NET MVC

This article explains the following:

  • How to create a ASP.NET MVC Project
  • How to Add ADO.NET Entity Data Model
  • How to Add Controller
  • How to validate User Credentials
  • How to keep User Details in Sessions and display in User DashBoard

Step: Design your Database

Create the UserProfile table using the following script.

  1. Create Table UserProfile  
  2.     (  
  3.         UserId int primary key identity(1, 1),  
  4.         UserName varchar(50),  
  5.         Password varchar(50),  
  6.         IsActive bit  
  7.     )  
Insert user records using the following script.
  1. Insert into UserProfile  
  2. Select 'jaipal''jai1234', 1 Union All  
  3. Select 'praveen''praveen1234', 1 Union All  
  4. Select 'pruthvi''pruthvi1234', 1 
Step 1: Create Project

Go to FILE, New, then click on Project.
create project

Select Visual C#, Web under Installed templates. After that select ASP.NET MVC 4 Web Application, then mention the Application Name (MvcLoginAppDemo) and Solution Name as you wish, then click OK.

ASP.NET MVC 4 Web Application

Under Project template select a template as Basic, then view engine as Razor. Click OK.

select a template as Basic

Step 2: Add Entity Data Model
Go to Solution Explorer, Right Click on Project, Add, then select ADO.NET Entity Data Model.

select ADO.NET Entity Data Model
 
Give it a meaningful model name and then click on Add.

sampleDataModel

Select Generate from database and then click on Next.

Generate from database

Click on New Connection,

New Connection
 
After clicking on New Connection, we have to provide the following Connection Properties in the following wizard.
  • Provide the Server name.
  • Select the "Use SQL Server Authentication" radio button.
  • Enter the User name and Password in the password text box.
  • Check the "Save my password" checkbox.
  • Select the "Select or enter a database name:" radio button.
  • Select the database to which you want to set the connection.
  • Click on the "Test Connection" button to ensure the connection can be established.
  • Then click OK.

Test Connection

Select radio button: Yes include the sensitive data in the connection string.

Choose your data connection

Choose your database objects, as in the following image.
 
Choose your database objects

 Click on Finish. At this point UserProfie entity will be created.

UserProfie

Step 3: Add a Controller

Go to Solution Explorer, Right click on Controller folder, Add and then click on Controller.
( Or ) Simply use shortcut key Ctrl + M, Ctrl + C,

Add a Controller

Provide the Controller Name, and Scaffolding template as Empty MVC Controller. Then click on Add.

Empty MVC Controller

Write the following code in HomeController.
  1. using System.Linq;  
  2. using System.Web.Mvc;  
  3.   
  4. namespace MvcLoginAppDemo.Controllers  
  5. {  
  6.     public class HomeController: Controller  
  7.     {  
  8.         public ActionResult Login()  
  9.         {  
  10.             return View();  
  11.         }  
  12.   
  13.         [HttpPost]  
  14.         [ValidateAntiForgeryToken]  
  15.         public ActionResult Login(UserProfile objUser)   
  16.         {  
  17.             if (ModelState.IsValid)   
  18.             {  
  19.                 using(DB_Entities db = new DB_Entities())  
  20.                 {  
  21.                     var obj = db.UserProfiles.Where(a => a.UserName.Equals(objUser.UserName) && a.Password.Equals(objUser.Password)).FirstOrDefault();  
  22.                     if (obj != null)  
  23.                     {  
  24.                         Session["UserID"] = obj.UserId.ToString();  
  25.                         Session["UserName"] = obj.UserName.ToString();  
  26.                         return RedirectToAction("UserDashBoard");  
  27.                     }  
  28.                 }  
  29.             }  
  30.             return View(objUser);  
  31.         }  
  32.   
  33.         public ActionResult UserDashBoard()  
  34.         {  
  35.             if (Session["UserID"] != null)  
  36.             {  
  37.                 return View();  
  38.             } else  
  39.             {  
  40.                 return RedirectToAction("Login");  
  41.             }  
  42.         }  
  43.     }  
  44. }  
Step 4: Create Views

Create View for Login Action Method
Right click on the Login Action method, then click on Add View as in the following picture.

Create Views 

Create Strongly Typed View
  • View Name must be an action method name.
  • Select view engine as Razor.
  • Select Create a strongly typed view CheckBox .
  • Select Model class as UserProfile (MvcLoginAppDemo)
  • Select Scaffold template as Empty
  • Click on Add

add view

And write the following code in Login.cshtml (view). 
  1. @model MvcLoginAppDemo.UserProfile  
  2.   
  3. @{  
  4. ViewBag.Title = "Login";  
  5. }  
  6.   
  7. @using (Html.BeginForm("Login""Home", FormMethod.Post))  
  8. {  
  9. <fieldset>  
  10. <legend>Mvc Simple Login Application Demo</legend>  
  11.   
  12. @Html.AntiForgeryToken()  
  13. @Html.ValidationSummary(true)  
  14. @if (@ViewBag.Message != null)  
  15. {  
  16. <div style="border: 1px solid red">  
  17. @ViewBag.Message  
  18. </div>  
  19. }  
  20. <table>  
  21. <tr>  
  22. <td>@Html.LabelFor(a => a.UserName)</td>  
  23. <td>@Html.TextBoxFor(a => a.UserName)</td>  
  24. <td>@Html.ValidationMessageFor(a => a.UserName)</td>  
  25. </tr>  
  26. <tr>  
  27. <td>  
  28. @Html.LabelFor(a => a.Password)  
  29. </td>  
  30. <td>  
  31. @Html.PasswordFor(a => a.Password)  
  32. </td>  
  33. <td>  
  34. @Html.ValidationMessageFor(a => a.Password)  
  35. </td>  
  36. </tr>  
  37. <tr>  
  38. <td></td>  
  39. <td>  
  40. <input type="submit" value="Login" />  
  41. </td>  
  42. <td></td>  
  43. </tr>  
  44. </table>  
  45. </fieldset>  
  46. }  
Create View for UserDashBoard Action method same as login view. And write the following code in UserDashBoard.cshtml (View).
  1. @ {  
  2.     ViewBag.Title = "UserDashBoard";  
  3. }  
  4.   
  5. < fieldset >  
  6.     < legend > User DashBoard < /legend>  
  7.   
  8. @if(Session["UserName"] != null) { < text >  
  9.         Welcome @Session["UserName"].ToString() < /text>  
  10. } < /fieldset>  
Step 5: Set as StartUp Page

Go to Solution Explorer, Project, App_Start, then RouteConfig.cs  and change the action name from Index to Login (Login.cshtml as start up page).

Set as StartUp Page

Step 6: Run the Application

Run the Application 

Provide the user credentials and click on OK. If you provide the valid user credentials then the user name will be displayed on your dashboard.

user dashboard

Read my articles on SSRS: http://www.c-sharpcorner.com/UploadFile/44fb93/ssrs-tutorial-part-5-embedded-datasets/
I hope you enjoyed it. 

Up Next
    Ebook Download
    View all
    Learn
    View all