Introduction
Every real-world application needs:
User Registration
Login System
Session Management
Logout
Companies always ask this in interviews.
Students search this topic daily.
So this blog has high view potential.
What We Will Build
We will create:
User Registration
Login Page
Session Handling
Logout
Database Connection using ADO.NET
This is beginner-friendly and easy to understand.
Step 1: Create Database
Open SQL Server and run:
CREATE DATABASE LoginMVCDB;
USE LoginMVCDB;
CREATE TABLE Users
(
Id INT PRIMARY KEY IDENTITY(1,1),
Username NVARCHAR(100),
Email NVARCHAR(100),
Password NVARCHAR(100)
);
Explanation
IDENTITY(1,1)→ Auto-increment IDUsername→ Stores usernameEmail→ Stores emailPassword→ Stores password
Note: For learning purposes only. In real projects, always hash passwords.
Step 2: Create ASP.NET MVC Project
Open Visual Studio
Create New ASP.NET Web Application
Choose MVC Template
Step 3: Add Connection String
Open Web.config and add the following:
<connectionStrings>
<add name="dbcs"
connectionString="Data Source=YOUR_SERVER;Initial Catalog=LoginMVCDB;Integrated Security=True"
providerName="System.Data.SqlClient"/>
</connectionStrings>
Replace YOUR_SERVER with your SQL Server name.
Step 4: Create Model
Create User.cs inside the Models folder.
public class User
{
public int Id { get; set; }
public string Username { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
Why Model?
Model transfers data between:
Controller → View
View → Controller
Step 5: Create AccountController
Add namespaces:
using System.Configuration;
using System.Data.SqlClient;
using YourProjectName.Models;
Registration Feature
Registration GET Method
public ActionResult Register()
{
return View();
}
This shows an empty registration form.
Registration POST Method
[HttpPost]
public ActionResult Register(User user)
{
string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
string query = "INSERT INTO Users(Username,Email,Password) VALUES(@Username,@Email,@Password)";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("@Username", user.Username);
cmd.Parameters.AddWithValue("@Email", user.Email);
cmd.Parameters.AddWithValue("@Password", user.Password);
con.Open();
cmd.ExecuteNonQuery();
}
ViewBag.Message = "Registration Successful!";
return View();
}
Join the conversation! Your thoughts help the community grow.