How To Create Login Page In Mvc 5 With Database

Web Development Software

Creating a login page in MVC 5 with a database is an essential part of any web application that requires user authentication. In this article, I will guide you through the process of creating a robust login page using MVC 5 and a database, while sharing some personal insights and tips along the way.

Setting Up the Database

First, let’s start by setting up the database for our login page. We will be using Microsoft SQL Server for this example. Open up SQL Server Management Studio and create a new database. You can name it whatever you like, but for simplicity, let’s call it “LoginDB”.

Next, we need to create a table to store our user credentials. Execute the following SQL script in the “LoginDB” database:


CREATE TABLE Users (
Id INT IDENTITY(1,1) PRIMARY KEY,
Username NVARCHAR(50) NOT NULL,
Password NVARCHAR(50) NOT NULL
);

This table will have two columns, “Username” and “Password”, where we will store the user information.

Creating the MVC Project

Now that we have our database set up, let’s create an MVC 5 project in Visual Studio. Start by opening Visual Studio and selecting “New Project”. Choose the “ASP.NET Web Application” template and give your project a name. Make sure to select “MVC” as the project template and click “OK” to create the project.

Once the project is created, go to the “Models” folder and add a new class called “User.cs”. This class will represent our User model and will have properties for the username and password:


public class User
{
public string Username { get; set; }
public string Password { get; set; }
}

Now, let’s move on to the “Controllers” folder and add a new controller called “AccountController”. This controller will handle all the login related actions. Inside the “AccountController”, add the following code:


public class AccountController : Controller
{
// GET: Account/Login
public ActionResult Login()
{
return View();
}

// POST: Account/Login
[HttpPost]
public ActionResult Login(User user)
{
// Check if the user exists in the database
// Validate the user's credentials
// Redirect the user to the appropriate page

return RedirectToAction("Index", "Home");
}
}

The first method, “Login()”, will handle the GET request for the login page. We will create a separate view for this action shortly. The second method, “Login(User user)”, will handle the POST request when the user submits the login form. Here, you can implement the logic to check if the user exists in the database and validate their credentials.

Creating the Login View

Now, let’s create the login view. Right-click on the “Login” method inside the “AccountController” and select “Add View”. Choose a suitable name for the view and click “Add”. In the view, add the following code:


@model User

@using (Html.BeginForm("Login", "Account", FormMethod.Post))
{


@Html.TextBoxFor(model => model.Username)

@Html.PasswordFor(model => model.Password)


}

This code creates a simple login form with two fields for the username and password. When the form is submitted, it will invoke the “Login(User user)” method in the “AccountController”.

Implementing the Login Logic

Now that we have our view and controller set up, it’s time to implement the login logic. Update the “Login(User user)” method in the “AccountController” with the following code:


[HttpPost]
public ActionResult Login(User user)
{
using (var db = new SqlConnection("YourConnectionString"))
{
var query = "SELECT COUNT(1) FROM Users WHERE Username = @Username AND Password = @Password";
var parameters = new { Username = user.Username, Password = user.Password };
var result = db.ExecuteScalar(query, parameters);

if (result == 1)
{
// User is authenticated
// Set authentication cookie or session variable
return RedirectToAction("Index", "Home");
}
else
{
// Invalid credentials
ModelState.AddModelError("", "Invalid username or password.");
return View(user);
}
}
}

In this code, we are using ADO.NET to connect to the database and execute a SQL query to validate the user’s credentials. If the query returns a count of 1, it means that the user exists in the database and the credentials are valid. In that case, you can set an authentication cookie or session variable to keep the user logged in. If the query returns a count of 0, it means that the credentials are invalid, and we add a model error to the ModelState object and return the login view with the user model.

Conclusion

Creating a login page in MVC 5 with a database is a fundamental aspect of building secure web applications. By following the steps outlined in this article, you have learned how to set up the database, create the MVC project, implement the login logic, and create the login view. Remember to always handle user authentication securely and consider incorporating additional security measures like password hashing and account lockouts.

For more information on MVC 5 and user authentication, you can refer to the official Microsoft documentation: https://docs.microsoft.com/en-us/aspnet/mvc/overview/security