Login, Logout Page Using Master Page, Session, Sql Database in Asp.Net MVC step by step ?

Creating a login and logout system in ASP.NET MVC using a master page (layout), session management, and SQL Server as the database involves several steps. Below is a step-by-step guide:

Step 1: Setting Up the Project

  1. Create a New ASP.NET MVC Project:
    • Open Visual Studio.
    • Go to File > New > Project.
    • Select ASP.NET Web Application, name your project, and click OK.
    • Choose MVC and click OK.
  2. Add a SQL Server Database:
    • Right-click on the project in the Solution Explorer.
    • Click Add > New Item.
    • Choose SQL Server Database, name it (e.g., LoginDB.mdf), and click Add.
  3. Create User Table in the Database:
    • Right-click on the database in the Solution Explorer.
    • Click Open > Add New Table.
    • Create a table with columns: UserId (int, Primary Key, Identity), Username (nvarchar), and Password (nvarchar).
    • Save the table as Users.

Step 2: Setting Up Models

  1. Create a Model for User:
    • Right-click on the Models folder.
    • Click Add > Class, name it User.cs, and click Add

C-sharp Code:

using System.ComponentModel.DataAnnotations;

public class User

{

public int UserId { get; set; }

[Required(ErrorMessage = “Username is required”)]

public string Username { get; set; }

[Required(ErrorMessage = “Password is required”)]

[DataType(DataType.Password)]

public string Password { get; set; }

}

Step 3: Create a Data Access Layer

  1. Create a Context Class:
    • Add a class named UserContext.cs in the Models folder.

csharp

using System.Data.Entity;

public class UserContext : DbContext

{

public DbSet<User> Users { get; set; }

}

2. Configure the Connection String in Web.config:

  • Add the connection string inside the <configuration> section.

xml

<connectionStrings>

<add name=”UserContext”

connectionString=”Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=LoginDB;Integrated Security=True”

providerName=”System.Data.SqlClient” />

</connectionStrings>

Step 4: Setting Up Views

  1. Create the Master Layout (Shared Layout):
    • Open the _Layout.cshtml file in the Views/Shared folder.
    • Add basic HTML structure and links to login and logout actions.

html

<!DOCTYPE html>

<html>

<head>

<title>@ViewBag.Title</title>

<link href=”~/Content/Site.css” rel=”stylesheet” />

</head>

<body>

<div class=”navbar”>

<ul>

<li>@Html.ActionLink(“Home”, “Index”, “Home”)</li>

@if (Session[“Username”] != null)

{

<li>@Html.ActionLink(“Logout”, “Logout”, “Account”)</li>

}

else

{

<li>@Html.ActionLink(“Login”, “Login”, “Account”)</li>

}

</ul>

</div>

<div class=”content”>

@RenderBody()

</div>

</body>

</html>

2. Create Login View:

  • Create a new folder Account under the Views folder.
  • Right-click on the Account folder, click Add > View, name it Login.cshtml, and click Add.

html

@model YourNamespace.Models.User

@using (Html.BeginForm(“Login”, “Account”, FormMethod.Post))

{

<h2>Login</h2>

@Html.ValidationSummary(true)

<div>

@Html.LabelFor(m => m.Username)

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

</div>

<div>

@Html.LabelFor(m => m.Password)

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

</div>

<button type=”submit”>Login</button>

}

Step 5: Creating the Account Controller

  1. Create Account Controller:
    • Right-click on the Controllers folder.
    • Click Add > Controller, name it AccountController, and click Add.

C#:

using System.Linq;

using System.Web.Mvc;

using YourNamespace.Models;

public class AccountController : Controller

{

private UserContext db = new UserContext();

// GET: Account/Login

public ActionResult Login()

{

return View();

}

// POST: Account/Login

[HttpPost]

public ActionResult Login(User model)

{

if (ModelState.IsValid)

{

var user = db.Users

.FirstOrDefault(u => u.Username == model.Username && u.Password == model.Password);

if (user != null)

{

Session[“Username”] = user.Username;

return RedirectToAction(“Index”, “Home”);

}

else

{

ModelState.AddModelError(“”, “Invalid Username or Password”);

}

}

return View(model);

}

// GET: Account/Logout

public ActionResult Logout()

{

Session.Clear();

return RedirectToAction(“Login”);

}

}

Step 6: Update the Home Controller and View

  1. Modify the Home Controller:
    • Check session data to display personalized content.

C#:

public class HomeController : Controller

{

public ActionResult Index()

{

if (Session[“Username”] != null)

{

ViewBag.Message = $”Welcome, {Session[“Username”]}!”;

}

else

{

ViewBag.Message = “Welcome to the application!”;

}

return View();

}

}

2. Create Home Index View:

  • Modify the Index.cshtml in the Views/Home folder to display the message.

html:

<h2>@ViewBag.Message</h2>

Step 7: Run and Test the Application

  1. Run the Application:
    • Click Start in Visual Studio.
    • Test login with credentials that exist in the database.
    • Verify that sessions are handled correctly, and logout works as expected.

This guide sets up a basic login/logout system in ASP.NET MVC using session management and a SQL Server database. Let me know if you need further assistance or any clarifications!

Summary of Steps:

  1. Set Up Project:
    • Create a new ASP.NET MVC project in Visual Studio.
    • Add a SQL Server database (LoginDB.mdf) and create a Users table with UserId, Username, and Password columns.
  2. Create Models:
    • Create a User model class with properties for UserId, Username, and Password.
    • Create a UserContext class to handle database connections using Entity Framework.
  3. Configure Database Connection:
    • Add a connection string in Web.config to link the UserContext to the SQL Server database.
  4. Set Up Views:
    • Create a shared layout (_Layout.cshtml) with links for login and logout based on session status.
    • Create a Login.cshtml view in the Account folder to handle user login inputs.
  5. Create Account Controller:
    • Implement AccountController with Login and Logout actions:
      • Login Action: Validates the user and sets session data.
      • Logout Action: Clears session data.
  6. Modify Home Controller and Views:
    • Update the HomeController to display personalized content if a user is logged in.
    • Display welcome messages based on session data in the Index.cshtml view.
  7. Test the Application:
    • Run the application, test login functionality with database credentials, and ensure sessions and logout work as intended.

This solution provides a basic framework for handling authentication in an ASP.NET MVC application via sessions and SQL Server.

Leave a Comment

Your email address will not be published. Required fields are marked *