articles

Home / DeveloperSection / Articles / Implement Login Page Using Entity FrameWork in MVC

Implement Login Page Using Entity FrameWork in MVC

Rahul Pal 26663 14-Dec-2017
In this article I m explaining how  create a custom login page with Entity Framework and validation also
Step 1:
 First create a database structure and give the name EmployeeDB
  CREATE TABLE [dbo].[TblEmployee](

 [EmployeeId] [int] Primary Key IDENTITY(1,1) NOT NULL,
 [EmployeeName] [varchar](50) NULL,
 [FatherName] [varchar](50) NULL,
 [DOB] [datetime] NULL,
 [MobileNo] [int] NULL,
 [Age] [int] NULL,
 [EmailId] [varchar](50) NULL,
 [Password] [varchar](500) NULL)

    Step 2: First Create Our Employee Model, Right Click on Model Folder, then Select Class and Name it EmployeeModel

Implement Login Page Using Entity FrameWork in MVC

Step 3:

Your EmployeeModel.cs class should be look like this code snippets, for validation you need to import

Using System.ComponentModel.dataAnnotation.for required field you can use Like [Required(ErrorMessage=”This is your error message”)], I my cs I applied regular Expression, required, range etc.

using System;

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace MvApp1.Models
{
    public partial class Login
    {
        [Required(ErrorMessage="User Name is Required")]
        public string UserName { get; set; }

        [Required(ErrorMessage="Password is Required")]
        public string Password { get; set; }
    }
    public partial class Employee
    {
        public int EmployeeId { get; set; }

        [Display(Name="Employee Name")]
        [Required(ErrorMessage="Employee Name Is Required")]
        public string EmployeeName { get; set; }

        [Display(Name="Father Name")]
        [Required(ErrorMessage = "Father Name Is Required")]
        public string FatherName { get; set; }

        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:MM-dd-yyyy}")]
        [Display(Name="Date Of Birth")]
        [Required(ErrorMessage = "Date Of Birth Is Required")]
        public string DOB { get; set; }

        [Display(Name="Mobile No")]
        [Required(ErrorMessage = "Mobile No Is Required")]
        public int MobileNo { get; set; }

        [Display(Name="Age")]
        [Required(ErrorMessage = "Employee Name Is Required")]
        public int Age { get; set; }

        [Display(Name="Email Id")]
        [RegularExpression(@"^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-‌​]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$", ErrorMessage = "Email is not valid")]
        [Required(ErrorMessage = "Employee Name Is Required")]
        public string EmailId { get; set; }

        [Display(Name = "Password")]
        [Required(ErrorMessage = "Password is required")]
        public string Password { get; set; }
    }

}

Step 4:

Create Controller :

   Now right click on controller folder and select a controller

Implement Login Page Using Entity FrameWork in MVC

Step 4: Scaffold window will open. Here we choose an Empty Controller and Name It HomeController and click On Add Button

Implement Login Page Using Entity FrameWork in MVC

Your controller look Like This as Shown in the Below image and write a code for login

using System;

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvApp1.Models;
using System.IO;
using System.Text;
using System.Security.Cryptography;

namespace MvApp1.Controllers
{
    public class LoginController : Controller
    {
        //
        // GET: /Login/
         EmployeeDBEntities Db = new EmployeeDBEntities();
        public ActionResult LoginEmployee()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LoginEmployee(Login LoginVar)
        {

            var result1 = (from emp in Db.TblEmployees where emp.EmailId==LoginVar.UserName select emp.Password).FirstOrDefault();
            string DPassword = Decrypt(result1);
           // Db.TblEmployees.Where(m=>m.EmailId==LoginVar.UserName && m.Password==LoginVar.Password).FirstOrDefault()
            if (DPassword == LoginVar.Password)
            {
                return RedirectToAction("EmployeeDetails", "Employee", new { area = "Admin" });
            }
            else
            {
                ViewBag.Message = string.Format("UserName and Password is incorrect");
                return View();
            }

        }

        [NonAction]
        public string Decrypt(string cipherText)
        {
            if (cipherText != null)
            {
                string EncryptionKey = "MAKV2SPBNI99212";
                byte[] cipherBytes = Convert.FromBase64String(cipherText);
                using (Aes encryptor = Aes.Create())
                {
                    Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                    encryptor.Key = pdb.GetBytes(32);
                    encryptor.IV = pdb.GetBytes(16);
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                        {
                            cs.Write(cipherBytes, 0, cipherBytes.Length);
                            cs.Close();
                        }
                        cipherText = Encoding.Unicode.GetString(ms.ToArray());
                    }
                }
                return cipherText;
            }
            return null;
        }
    }
}

Step 5: For communicating database we use Entity Frame Work, Right click on model folder and  select Ado.net Entity Model and name it EmployeeDB

Implement Login Page Using Entity FrameWork in MVC

Implement Login Page Using Entity FrameWork in MVC

Step 6: After clicking ok button then Entity DataModel Wizard Is open and then press Next Button

Then Click on New Connection String

Implement Login Page Using Entity FrameWork in MVC

Step 7: After Click New Connection String Connection Properties Tab Is Open

  ->Select Server Name

->Select Windows authentication if you r using Local Server, if you are use Remote Server then Select SQL Server Authentication 

Then Select a Database and press OK

Implement Login Page Using Entity FrameWork in MVC

Step 8: After Pressing Ok, again Press Next button, Then Select a Table which u want in your EntitydataModel

Implement Login Page Using Entity FrameWork in MVC

Step 9: In previous step we create home Controller, in that Home Controller Write a Code for Login in HomeController

HomeController.cs

Public class LoginController: Controller

    {
        //
        // GET: /Login/
         EmployeeDBEntities Db = new EmployeeDBEntities();
        public ActionResult LoginEmployee()
        {
            return View();//For Rendering a Login View
        }

        [HttpPost]
        public ActionResult LoginEmployee(Login LoginVar)
        {

Var result=Db.TblEmployees.Where(m=>m.EmailId==LoginVar.UserName && m.Password==LoginVar.Password).FirstOrDefault()
if (result !== null)
            {
                return RedirectToAction("EmployeeDetails", "Employee);//I m returning to My Employee Action Method
            }
            else
            {
                ViewBag.Message = string.Format("UserName and Password is incorrect");
                return View();
            }

        }
}

Step 10: Now Right Click on LoginEmployee ,select a View and Click on Ok Your View is automatically create in your application

After adding view Design,In Your Login Page  place your design code in employee view,

For validation you can use ValidationSummay for Displaying Group Message at Top or Bottom in web app, and for inline validation you can use validatioMessage and validationmessagefor

Validationmessage: The Html.ValidationMessage () is an extension method, that is a loosely typed method. It displays a validation message if an error exists for the specified field in the ModelStateDictionary object.

ValidationMessageFor: The Html.ValidationMessageFor () is a strongly typed extension method. It displays a validation message if an error exists for the specified field in the ModelStateDictionary object.

Here I’m using a ValidationSummary

@model MvApp1.Models.Login

@{
    ViewBag.Title = "LoginEmployee";
}
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.16.0/jquery.validate.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validation.unobtrusive/3.2.6/jquery.validate.unobtrusive.min.js"></script>
<link rel="stylesheet" href="~/Content/Logincss.css" />
<div class="login-container">
    <section class="login" id="login">
        <header>
            <h2>Application Name</h2>
            <h4>Login</h4>
        </header>
        @using (@Html.BeginForm(null, null, FormMethod.Post, new { @class = "login-form" }))
        { @Html.ValidationSummary(false, "", new { @class = "text-danger" })
            @Html.TextBoxFor(m => m.UserName, new {@class = "login-input", placeholder = "user name" })


            @Html.PasswordFor(m => m.Password, new { @class = "login-input", placeholder = "Password" })


            <div class="text-danger">@ViewBag.Message</div>
            <div class="submit-container">
                <button type="submit" class="login-button">SIGN IN</button>
            </div>
        }

    </section>

</div>

Login Page

Implement Login Page Using Entity FrameWork in MVC








Updated 21-Apr-2020

Leave Comment

Comments

Liked By