Login Page In MVC Using Entity Framework

This article shows you how to create a login page in MVC.


Create Table in Database (SQL Server 2012)
  1. Create a database and name it as Login.
  2. Add table (here table name is tblLogin).
  3. Set primary key to Id column.
  4. Id as an Identity column with an Increment of 1 and a Seed of 1.


Create new project in Visual Studio 2015
  1. Go to File-> New-> Project -> Web-> ASP.NET MVC4 Web Application-> Entry Application Name-> OK.
  2. Select a template-> Empty-> add MVC folder-> OK.

MVC Folder is created.


Add Entity Data Model
  1. Right Click on Models Folder-> Add -> Visual C# -> Data-> ADO.NET Entity data Model-> Entry Name-> OK.

  2. Entity Data Model wizard -> Select EF Designer from Database-> Next.

  3. Choose your data connection-> Click New Connection.

  4. Enter your Server name-> Choose your authentication. I am using SQL Server authentication, so we need to provide the username and password-> Select your database-> Test Connection-> OK.

  5. Click Yes-> includes the sensitive data in the connection string->next->Choose version of Entity framework.

  6. Include Database objects to your model-> Finish.

  7. Visual Studio will generate a database diagram for the table.


Build the project and add the Controller.
  1. Select MVC5 Controller Empty-> Add -> Write Controller Name-> Add.

  2. Once you add the new controller, add code, mentioned below in Action Method (here Index).

Code Explanation

  1. Home Controller Class contains two Action methods. First Action method is [HttpGet], when you run the Application, this method will be executed. Second Action method is [HttpPost], when the user clicks login button; this Action method will be executed.
  2. Modelstate.IsValid property validates each model property against the validation attributes used in the model and it returns true or false.
  3. SaveChanges() method is called to save the data into the database.

Step 5 Now we need to add the view.

  1. Click right button on Index Action Method-> Add View.

  2. Choose Template, Model class, Data context class.

  3. The following is the view code, which displays the login details.