This article shows you how to create a login page in MVC.
STEP 1
Create Table in Database (SQL Server 2012)
- Create a database and name it as Login.
- Add table (here table name is tblLogin).
- Set primary key to Id column.
- Id as an Identity column with an Increment of 1 and a Seed of 1.
STEP 2
Create new project in Visual Studio 2015
- Go to File-> New-> Project -> Web-> ASP.NET MVC4 Web Application-> Entry Application Name-> OK.
- Select a template-> Empty-> add MVC folder-> OK.
MVC Folder is created.
STEP 3
Add Entity Data Model
- Right Click on Models Folder-> Add -> Visual C# -> Data-> ADO.NET Entity data Model-> Entry Name-> OK.
- Entity Data Model wizard -> Select EF Designer from Database-> Next.
- Choose your data connection-> Click New Connection.
- 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.
- Click Yes-> includes the sensitive data in the connection string->next->Choose version of Entity framework.
- Include Database objects to your model-> Finish.
- Visual Studio will generate a database diagram for the table.
STEP 4
Build the project and add the Controller.
- Select MVC5 Controller Empty-> Add -> Write Controller Name-> Add.
- Once you add the new controller, add code, mentioned below in Action Method (here Index).
Code Explanation
- 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.
- Modelstate.IsValid property validates each model property against the validation attributes used in the model and it returns true or false.
- SaveChanges() method is called to save the data into the database.
Step 5 Now we need to add the view.
- Click right button on Index Action Method-> Add View.
- Choose Template, Model class, Data context class.
- The following is the view code, which displays the login details.
OUTPUT