Monday, 22 June 2015

How to create a login page using asp.net mvc 4

INTRODUCTION

In this post, I am explain how to create a login page using asp.net mvc 4.

STEPS :

STEP - 1 : CREATE NEW PROJECT.

Go to File > New > Project > Select asp.net MVC4 web application > Entry Application Name > Click OK > Select Internet Application > Select view engine Razor > OK

STEP-2: ADD A DATABASE.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

STEP-3: CREATE TABLE FOR FETCH DATA.

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok. 
In this example, I have used one tables as below

STEP-4: ADD ENTITY DATA MODEL.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish. 

STEP-5: APPLY VALIDATION ON MODEL.

Open your model and add validation. Please follow below code 

  1. namespace MVCLogin
  2. {
  3. using System;
  4. using System.Collections.Generic;
  5. using System.ComponentModel.DataAnnotations;
  6.  
  7. public partial class User
  8. {
  9. public int UserID { get; set; }
  10. public string FullName { get; set; }
  11. [Required(ErrorMessage="Please Provide Username", AllowEmptyStrings=false)]
  12. public string Username { get; set; }
  13. [Required(ErrorMessage="Please provide password", AllowEmptyStrings=false)]
  14. [DataType( System.ComponentModel.DataAnnotations.DataType.Password)]
  15. public string Password { get; set; }
  16. }
  17. }

STEP-6: CREATE A CONTROLLER .

Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > Controller > Enter Controller name > Select Templete "empty MVC Controller"> Add.

Here I have used existing controller "Home Controller" 

STEP-7: ADD NEW ACTION INTO YOUR CONTROLLER FOR GET METHOD

Here I have added "Login" Action into "Home" Controller. Please write this following code 

  1. public class HomeController : Controller
  2. {
  3. public ActionResult Login()
  4. {
  5. return View();
  6. }
  7. }

STEP-8: ADD VIEW FOR LOGIN ACTION & DESIGN FOR CREATE LOGIN SCREEN.

Right Click on Action Method (here right click on Login action) > Add View... > Enter View Name > Select View Engine (Razor) > Check "Create a strong-typed view" > Select your model class > Add. 
HTML Code 
  1. @model MVCLogin.User
  2. @{
  3. ViewBag.Title = "Login";
  4. }
  5.  
  6. <h2>Login</h2>
  7.  
  8. @using (Html.BeginForm("Login","Home", FormMethod.Post))
  9. {
  10. //this is for create form tag
  11. @Html.AntiForgeryToken() // this is for prevent CSRF attack
  12. @Html.ValidationSummary(true)
  13. if (@ViewBag.Message != null)
  14. {
  15. <div style="border:1px solid red">
  16. @ViewBag.Message
  17. </div>
  18. }
  19. <table>
  20. <tr>
  21. <td>@Html.LabelFor(a=>a.Username)</td>
  22. <td>@Html.TextBoxFor(a=>a.Username)</td>
  23. <td>@Html.ValidationMessageFor(a=>a.Username)</td>
  24. </tr>
  25. <tr>
  26. <td>
  27. @Html.LabelFor(a=>a.Password)
  28. </td>
  29. <td>
  30. @Html.PasswordFor(a=>a.Password)
  31. </td>
  32. <td>
  33. @Html.ValidationMessageFor(a=>a.Password)
  34. </td>
  35. </tr>
  36. <tr>
  37. <td></td>
  38. <td>
  39. <input type="submit" value="Login" />
  40. </td>
  41. <td></td>
  42. </tr>
  43. </table>
  44. }
  45.  
  46. @* This below line is for create javascript section *@
  47.  
  48. @section Scripts{
  49. @Scripts.Render("~/bundles/jqueryval")
  50. }

STEP-9: ADD NEW ACTION INTO YOUR CONTROLLER FOR POST METHOD (FOR LOGIN)

Here I have added "Login" Action with Model Parameter (here "User") into "Home" Controller. Please write this following code 

  1. [HttpPost]
  2. [ValidateAntiForgeryToken]
  3. public ActionResult Login(User u)
  4. {
  5. // this action is for handle post (login)
  6. if (ModelState.IsValid) // this is check validity
  7. {
  8. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  9. {
  10. var v = dc.Users.Where(a => a.Username.Equals(u.Username) && a.Password.Equals(u.Password)).FirstOrDefault();
  11. if (v != null)
  12. {
  13. Session["LogedUserID"] = v.UserID.ToString();
  14. Session["LogedUserFullname"] = v.FullName.ToString();
  15. return RedirectToAction("AfterLogin");
  16. }
  17. }
  18. }
  19. return View(u);
  20. }

STEP-10: ADD ANOTHER NEW ACTION INTO YOUR CONTROLLER FOR SHOW VIEW AFTER LOGIN.

Here I have added "AfterLogin" Action. 

  1. public ActionResult AfterLogin()
  2. {
  3. if (Session["LogedUserID"] != null)
  4. {
  5. return View();
  6. }
  7. else
  8. {
  9. return RedirectToAction("Index");
  10. }
  11. }

STEP-11: ADD VIEW FOR ACTION "AFTERLOGIN" FOR SHOW VIEW AFTER LOGIN.

Right Click on Action Method (here right click on AfterLogin action) > Add View... > Enter View Name > Select View Engine (Razor) > Add. 

  1. @{
  2. ViewBag.Title = "AfterLogin";
  3. }
  4.  
  5. <h2>After Login</h2>
  6. @if (Session["LogedUserFullname"] != null)
  7. {
  8. <text>
  9. Welcome @Session["LogedUserFullname"].ToString()
  10. </text>
  11. }

STEP-12: RUN APPLICATION.

0 comments: