How to create a login page using asp.net mvc 4



Introduction

This is the 2nd part of this series, where I am going to explain how to create a login page using asp.net MVC.

You know, Dotnet awesome is a platform to learn, read and explore contents related to web development. Here in this series "Implement basic functionality in asp.net MVC application", I have explained how to create some very basic functionality like create a registration page, login page, file upload page etc., especially for beginners.

I have explained following articles in the series "Implement basic functionality in asp.net MVC application"
  1. How to create a User Registration page using asp.net mvc
  2. How to create a login page using asp.net mvc
  3. How to create career page with Upload file (CV) in MVC
  4. How to create Feedback page with cascade dropdownlist in MVC.
  5. How to display database data in webgrid in mvc

Steps :

Step - 1: Create New Project.

Go to File > New > Project > Select asp.net MVC4 web application > Entry Application Name > Click OK > Select Internet Application > Select view engine Razor > OK

Step-2: Add a Database.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-3: Create table for fetch data.

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.
In this example, I have used one table as below


Step-4: Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-5: Apply validation on model.

Open your model and add validation. Please follow below code

namespace MVCLogin
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;

    public partial class User
    {
        public int UserID { get; set; }
        public string FullName { get; set; }
        [Required(ErrorMessage = "Please Provide Username", AllowEmptyStrings = false)]
        public string Username { get; set; }
        [Required(ErrorMessage = "Please provide password", AllowEmptyStrings = false)]
        [DataType(System.ComponentModel.DataAnnotations.DataType.Password)]
        public string Password { get; set; }
    }
}

Step-6: Create a Controller.

Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > Controller > Enter Controller name > Select Templete "empty MVC Controller"> Add.

Here I have used existing controller "Home Controller"

Step-7: Add new action into your controller for Get Method

Here I have added "Login" Action into "Home" Controller. Please write this following code

public class HomeController : Controller
{
    public ActionResult Login()
    {
        return View();
    }
}

Step-8: Add view for Login Action & design for creating login screen.

Right Click on Action Method (here right click on Login action) > Add View... > Enter View Name > Select View Engine (Razor) > Check "Create a strong-typed view" > Select your model class > Add.
HTML Code
@model MVCLogin.User
@{
    ViewBag.Title = "Login";
}

<h2>Login</h2>

@using (Html.BeginForm("Login", "Home", FormMethod.Post))
{
    //this  is for create form tag
    @Html.AntiForgeryToken()          // this is for prevent CSRF attack
    @Html.ValidationSummary(true)
    if (@ViewBag.Message != null)
    {
    <div style="border: 1px solid red">
        @ViewBag.Message
    </div>
    }
    <table>
        <tr>
            <td>@Html.LabelFor(a => a.Username)</td>
            <td>@Html.TextBoxFor(a => a.Username)</td>
            <td>@Html.ValidationMessageFor(a => a.Username)</td>
        </tr>
        <tr>
            <td>
                @Html.LabelFor(a => a.Password)
            </td>
            <td>
                @Html.PasswordFor(a => a.Password)
            </td>
            <td>
                @Html.ValidationMessageFor(a => a.Password)
            </td>
        </tr>
        <tr>
            <td></td>
            <td>
                <input type="submit" value="Login" />
            </td>
            <td></td>
        </tr>
    </table>
}

@* This below line is for create javascript section *@

@section Scripts{
    @Scripts.Render("~/bundles/jqueryval")
}

Step-9: Add new action into your controller for POST Method (for login)

Here I have added "Login" Action with Model Parameter (here "User") into "Home" Controller. Please write this following code

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(User u)
{
    // this action is for handle post (login)
    if (ModelState.IsValid) // this is check validity
    {
        using (MyDatabaseEntities dc = new MyDatabaseEntities())
        {
            var v = dc.Users.Where(a => a.Username.Equals(u.Username) && a.Password.Equals(u.Password)).FirstOrDefault();
            if (v != null)
            {
                Session["LogedUserID"] = v.UserID.ToString();
                Session["LogedUserFullname"] = v.FullName.ToString();
                return RedirectToAction("AfterLogin");
            }
        }
    }
    return View(u);
}

Step-10: Add another new action into your controller for Show view after login.

Here I have added "AfterLogin" Action.

public ActionResult AfterLogin()
{
    if (Session["LogedUserID"] != null)
    {
        return View();
    }
    else
    {
        return RedirectToAction("Index");
    }
}

Step-11: Add view for action "AfterLogin" for Show view after login.

Right Click on Action Method (here right click on AfterLogin action) > Add View... > Enter View Name > Select View Engine (Razor) > Add.

@{
    ViewBag.Title = "AfterLogin";
}

<h2>After Login</h2>
@if (Session["LogedUserFullname"] != null)
{
    <text>
    Welcome @Session["LogedUserFullname"].ToString()
    </text>
}

Step-12: Run Application.

Download Application     Live Demo

If you are working on AngularJS application and wants to create a login page in angularjs with asp.net mvc as server side, this link will be useful to you how to create a login page using AngularJS in MVC4 application. 




Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.