---
title: "Implement Login Page Using Entity FrameWork in MVC"  
description: "In this article we define Implementation of Login Page Using Entity FrameWork in MVC"  
author: "Rahul Pal"  
published: 2017-12-14  
updated: 2020-04-21  
canonical: https://www.mindstick.com/articles/12721/implement-login-page-using-entity-framework-in-mvc  
category: "c#"  
tags: ["asp.net mvc", "mvc", "entity framework"]  
reading_time: 9 minutes  

---

# Implement Login Page Using Entity FrameWork in MVC

In this article I m explaining how create a custom login page with [Entity Framework](https://www.mindstick.com/articles/1566/crud-operations-using-entity-framework-code-first-approach) 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](https://www.mindstick.com/mindstickarticle/8a5e645c-748e-4e9c-a788-ca84d5e7349a/images/ed2058f3-e27e-44c4-ad9e-b0416ddbef39.png)

## 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](https://www.mindstick.com/mindstickarticle/8a5e645c-748e-4e9c-a788-ca84d5e7349a/images/9f78196f-8385-404f-bd5b-9a7d3904ea94.png)

**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](https://www.mindstick.com/mindstickarticle/8a5e645c-748e-4e9c-a788-ca84d5e7349a/images/2f036d14-537c-4191-9256-8a601d1ae3ed.png)

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](https://www.mindstick.com/mindstickarticle/8a5e645c-748e-4e9c-a788-ca84d5e7349a/images/762daaba-8769-48ce-a4ac-74a1235145bd.png)

![Implement Login Page Using Entity FrameWork in MVC](https://www.mindstick.com/mindstickarticle/8a5e645c-748e-4e9c-a788-ca84d5e7349a/images/ddb21267-7dbf-4689-8aec-dd6c0375ccd7.png)

**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](https://www.mindstick.com/mindstickarticle/8a5e645c-748e-4e9c-a788-ca84d5e7349a/images/16421500-71de-470e-bc59-12f559a76e15.png)

**Step 7:** After Click New [Connection String](https://www.mindstick.com/articles/17/connection-string) Connection Properties Tab Is Open

->Select [Server Name](https://answers.mindstick.com/qa/110129/how-to-change-discord-server-name)

->Select Windows authentication if you r using Local Server, if you are use Remote Server then Select [SQL Server](https://www.mindstick.com/articles/34/create-table-in-microsoft-sql-server) Authentication

Then Select a Database and press OK

![Implement Login Page Using Entity FrameWork in MVC](https://www.mindstick.com/mindstickarticle/8a5e645c-748e-4e9c-a788-ca84d5e7349a/images/f3d217a8-c595-485b-8632-e83f1d76d99e.png)

**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](https://www.mindstick.com/mindstickarticle/8a5e645c-748e-4e9c-a788-ca84d5e7349a/images/ff60e193-7db0-4fdf-b44b-626f159b2463.png)

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](https://yourviews.mindstick.com/view/85403/what-is-your-view-about-84-lakh-yonis-in-hinduism) is automatically create in [your application](https://answers.mindstick.com/qa/95487/how-do-you-troubleshoot-when-your-application-link-is-not-responding)

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](https://www.mindstick.com/blog/74221/tips-on-real-estate-web-app-development), and for inline validation you can use validatioMessage and [validationmessagefor](https://www.mindstick.com/forum/573/refactor-html-labelfor-editorfor-validationmessagefor-into-partial-view)

Validationmessage: The Html.ValidationMessage () is an [extension method](https://www.mindstick.com/articles/22/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](https://www.mindstick.com/forum/298/strongly-typed-view-in-mvc) 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](https://www.mindstick.com/mindstickarticle/8a5e645c-748e-4e9c-a788-ca84d5e7349a/images/5da3338e-0c5f-4e98-b19b-1914499a444a.png)\

\

\

\

\

\

\

---

Original Source: https://www.mindstick.com/articles/12721/implement-login-page-using-entity-framework-in-mvc

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
