Thursday, April 16, 2015

Create a custom login page in MVC

Introduction: In this article today I am going to explain how to create a custom login page in MVC
Create a custom login page in MVC

Description:

To create a login page follow the below given steps:


Step 1: Models Class
I have a UserRegistration.cs class file in Models. Validations are applied to class. See the below given code of class:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
public class User_Registration
    {
        [Key]
        public int Id { get; set; }
       [Required(ErrorMessage="Please Enter UserName")]
        public string User_Name { get; set; }
          [Required(ErrorMessage = "Please Enter First Name")]
        public string First_Name { get; set; }
      [Required(ErrorMessage = "Please Enter Last Name")]
        public string Last_Name { get; set; }
       [DataType(DataType.Upload)]
        public string Profile_Image { get; set; }
    [Required(ErrorMessage = "Please Enter Password")]
        public string Password { get; set; }
        [RegularExpression(@"^([0-9a-zA-Z]([\+\-_\.][0-9a-zA-Z]+)*)+@(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]*\.)+[a-zA-Z0-9]{2,3})$",ErrorMessage = "Please Enter Email ID")]
        public string EmailId { get; set; }
       [Required(ErrorMessage = "Please Enter Gender")]
        public string Sex { get; set; }
        [Required(ErrorMessage = "Please Select Qualification")]
        [ForeignKey("Master_Qualification")]
        public int EducationId { get; set; }
       [Required(ErrorMessage = "Please Select Country")]
        [ForeignKey("Master_Country")]
        public int CountryId { get; set; }
       [Required(ErrorMessage = "Please Enter Phone No")]
        public int Phone_No { get; set; }
     [Required(ErrorMessage = "Please Select the terma & Conditions")]
        public bool Terms { get; set; }

        public virtual Master_Country Master_Country { get; set; }
        public virtual Master_Qualification Master_Qualification { get; set; }
    }

Step 2: Add a Controller
Add a controller to Controllers folder. I add an empty LoginController.cs and add new actions for Login, Welcome and Logout to Controller. Write the code as shown below:
using UserRegistration.Models;
public class LoginController : Controller
    {
        //
        // GET: /Login/
        private ProjectContext db = new ProjectContext();
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult UserLogin()
        {
            return View();
        }
        [HttpPost]
        public ActionResult UserLogin(User_Registration user)
        {
            if (ModelState.IsValidField("Username") && ModelState.IsValidField("Password"))
            {
                var login = db.User_Registrations.Where(u => u.User_Name.Equals(user.User_Name) && u.Password.Equals(user.Password)).FirstOrDefault();
                if (login != null)
                {
                    Session["UserID"] = login.Id.ToString();
                    Session["UserName"] = login.User_Name.ToString();
                    return RedirectToAction("WelcomeUser");
                }
                else
                {
                    ModelState.AddModelError("", "Username and Password does not match");
                }
            }
            return View(user);
        }
        public ActionResult WelcomeUser()
        {
            if (Session["UserID"] != null)
            {
                return View();
            }
            else
            {
                return RedirectToAction("UserLogin");
            }
        }
        public ActionResult LogOut()
        {
            Session.Abandon();
            return RedirectToAction("UserLogin", "UserRegistration");
        }
    }

Step 3: Add view
Add view for Login and Welcome actions.

UserLogin.cshtml
@model UserRegistration.Models.User_Registration

@{
    ViewBag.Title = "Login Page";
}
<style>
    .login-btn
    {
       background-color:#808080;
       width:100px;
       height:36px;
       color:#fff;
       border-radius:5px;
       font-weight:bold;
       font-size:15px;
    }
</style>
<fieldset>
    <legend>Login</legend>


@using (Html.BeginForm("Userlogin", "Login", FormMethod.Post))
{
   @Html.ValidationSummary(true)
<table>
  <tr>
   <td><b>UserName :-</b></td>
   <td>@Html.TextBoxFor(a=>a.User_Name)</td>
   <td>@Html.ValidationMessageFor(a=>a.User_Name)</td>
  </tr>
  <tr>
   <td>
   <b>Password :-</b>
   </td>
   <td>
    @Html.PasswordFor(a=>a.Password)
   </td>
   <td>
    @Html.ValidationMessageFor(a=>a.Password)
   </td>
  </tr>
  <tr>
   <td></td>
   <td>
    <input type="submit" value="Login" class="login-btn" />
   </td>
   <td></td>
  </tr>
 </table>
    }
    </fieldset>

WelcomeUser.cshtml
@model UserRegistration.Models.User_Registration

@{
    ViewBag.Title = "Welcome Page ";
}

<table style="width:100%">   
<tr><td style="width:80%"></td><td style="width:20%">
@if (Session["UserName"] != null)
{
 <text>
  Welcome <b>@Session["UserName"].ToString() </b>
 </text>
}
@Html.ActionLink("Logout", "LogOut", "UserRegistration")</td></tr>
<tr><td></td><td></td></tr>
<tr><td></td><td></td></tr>
<tr><td></td><td></td></tr>

</table>
Now build the project and run. Check the result.

Download


No comments:

Post a Comment