Simple Login Application in ASP.NET MVC

In this tutorial, we are going to create a simple asp.net MVC login Application. We will use models with data annotations.

If you want to familiarize yourself with this framework visit this article. ASP.NET MVC default template structure

Project Summary:

  • HomeController.cs -> Default MVC controller
  1. Index() -> load default view of the HomeController. Where view is located at Views->Home->index.cshtml
  2. Index(LoginModel model)-> This received the user’s data input from our login form using a POST request. This returns the controller’s default view, which is the login form, if the login details are incorrect or redirect to the landing page if successfully authenticated.
  3. AccountVerification()-> This function return boolean(true or false). This check the login credential if it is valid or not.
  4. Welcome_Page()-> This call’s the landing view if the user is successfully logging in.
  • LoginModel()-> This is a class where properties are being declared. (public string Email{get;set}). We will use this model to bind with our login view form.
  • chtml-> This is the Default view of Home Controller (Location Views->Home->Index.cshtml.

Welcome_Page.cshtml -> view for Welcome_Page ActionResult this serve as our UserInterface for our landing page.(Location Views->Home->Welcome_Page.cshtml)

Project output:

MVC Login Form

Let’s Start:

Note: You can name your project anything you prefere.In my case I name it Simple MVC login implementation.

  1. First, create a new project in Visual Studio 2013 using a default MVC Template. If this is your first time to create one, visit this blog for tutorial in creating a project How to start with Asp.Net MVC application.

2. After successfully creating a project go to solution explorer and navigate to Model folder and add new class for our model. Right click on Model folder choose add then select Class.

Add Model

3. Name your class as LoginModel.

Name class as LoginModel

4. Open your LoginModel class and copy and paste code below:

LoginModel.cs Code:

  • Declare Email and password properties and define property requirements.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace Simple_MVC_Login_implementation.Models
{
    public class LoginModel
    {
        [Required]
        [Display(Name="Email")]
        public string  Email { get; set; }
        
        [Required]
        [DataType(DataType.Password)]
        [Display(Name="Password")]
        public string  Password { get; set; }
    }
}

Note:

  • using System.ComponentModel.DataAnnotations; -> This is responsible for setting attribute and requirements for your properties. Ex.  [Required]

5. Next, go to Controller folder and open file HomeController. HomeController is the default controller for asp.net mvc template. This is where we put all the process we need for the project.

Controller

6. Replace the code from your HomeController with the code below. The code below contains three action result.

HomeController function details:
  • Index() -> This return Default view of HomeController which is our Login Form
  •  Index(LoginModel model) – > This receive model data from our view  (Login Form) using a post request. It also redirects the page to our welome_page view if credential is successfully validated.
  • AccountVerification(string Email,string password) – > This function use to verify if email and password match to your valid credential.
  • ModelState.IsValid -> Controller properties that check model property state.

Home Controller Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Simple_MVC_Login_implementation.Models;

namespace Simple_MVC_Login_implementation.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Index(LoginModel model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }
            if (AccountVerification(model.Email, model.Password))
            {
                return RedirectToAction("Welcome_Page",model);
            }
            else
            {
                ModelState.AddModelError("", "Invalid Input Details");
            }

            return View();    
        }

        public bool AccountVerification(string Email,string password)
        {
            bool result = false;

            if (Email == "[email protected]" && password == "12345")
            {
                result = true;
            }

            return result;
        }

        public ActionResult Welcome_Page(LoginModel model)
        {

            return View(model);
        }
       
    }
}

7. Open your HomeController default view which is index.cshtml located at your solution explorer Views->Home->Index.cshtml.

View Folder

8. Bind the model to the login view which is index.cshtml. To do so replace the code below to your index file.

  • @using Simple_MVC_Login_implementation.Models -> access model properties.
  • @model LoginModel-> Bind LoginModel to our View.

Simple login form using HTML Helper.

Output:

MVC Login Form
Index.cshtml Code:

Copy and paste code below to your index.cshtml.

@using Simple_MVC_Login_implementation.Models
@model LoginModel
@{
    ViewBag.Title = "Home Page";
}
<div class="row">
    <br/>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { @class = "form-horizontal",role="form" }))
    {
        <fieldset>
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })   <!--Enable Data Anotation-->
            <div class="form-group">
                @Html.LabelFor(m => m.Email, new { @class = "col-lg-2 control-label"})
                <div class="col-lg-10">
                    @Html.TextBoxFor(m => m.Email, new { @class = "form-control"})
                    @Html.ValidationMessageFor(m => m.Email, "", new { @class="text-danger"}) <!Display of Error Notification-->
                </div>
            </div>
            <div class="form-group">
                @Html.LabelFor(m => m.Password, new { @class = "col-lg-2 control-label"})
                <div class="col-lg-10">
                 @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
                 @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })<!Display of Error Notification-->
                </div>
            </div>
            <div class="form-group">
                <div class="col-lg-10 col-lg-offset-2">
                    <button type="submit" class="btn btn-primary">Login</button>
                </div>
            </div>
        </fieldset>
    }
</div>

9. Lastly, create a landing page or welcome page for your application. This will be displayed after a user has successfully validated his credentials.

  • To add new View, from your solution explorer right click on the Home folder inside the views folder and choose Add then select MVC 5 View Page with Layout (Razor).
Manual adding of View
  • Then choose layout for your view.
Name View
  • Then choose layout for your view.
Choose layout
  • Open Welcome_Page view. Copy and paste code below:
Welcome_page
Welcome_Page Code:
  • Display welcome message including the email used to log in.
@using Simple_MVC_Login_implementation.Models
@model LoginModel
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div class="jumbotron">
    <h2>Welcome To My Page!</h2>
    <h3>You are Log in as @Model.Email</h3>
</div>

Output:

Welcome Page

You’re all set! We have successfully created a simple concept of asp.net MVC login Application.Run the project by pressing F5 in your keyboard. If you have any questions just leave a comment below.Thank you for reading hopes this helps.

Leave a Comment

%d bloggers like this: