This is a quick simple example of how to implement it in ASP.NET MVC project.

In this project I am using Code first approach for creating database and table.

Please implement the following steps to create a Login and Registration Form:

Open Microsoft Visual Studio 2012 and Select New Project and Select Web from the Installed Templates and then Select ASP.NET MVC 4 Web Application and Enter the project name “LoginForm” in the Name textbox and Click OK.

Login and Registration in ASP.Net MVC

After select the project you can see the following (New ASP.NET MVC 4 Project)


dialog box:

Select Empty from the Select a template option à Select ASPX view engine à Click OK.

Login and Registration in ASP.Net MVC


Add a new Controller in your project and enter the controller name as “AccountController” as shown in the below figure:

Login and Registration in ASP.Net MVC


After adding a controller add a Model in your project and enter the model class name as “UserModel.cs”.

Login and Registration in ASP.Net MVC


You also have to configure your web.config and Globax.asax file for the implementation of this project:

Add connectionStrings element under configuration tag


and authentication element under system.web tag.


<authentication mode="Forms">
      <forms name="Demo" loginUrl="~/Account/Login" protection="All" timeout="30"/>
    </authentication>
  <connectionStrings>
    <add name="UserEntity" connectionString="data source=MSCLIENT014;initial catalog=UserDb;user id=sa;password=mindstick@123" providerName="System.Data.SqlClient"/>
  </connectionStrings>

Change the RegisterRoutes definition in Global.asax file as show below:



        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Account", action = "Login", id =
            UrlParameter.Optional }
            );
        }


In the Model class add the properties, methods and class as I did in the below Model (UserModel) class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations.Schema;
namespace MvcApplication2.Models
{
   public class Designation
   {
 
       public int DesignationId { get; set; }
       public string Name { get; set; }
  public ICollection<User> Users { get; set; }
  }
 
   public partial class User
   {
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.None)]
       public int Id { get; set; }
       [Required(ErrorMessage = "Name is Require")]
       [RegularExpression(@"^[a-zA-Z\s]+$", ErrorMessage = "Name Field Accept Only Alphabet...")]
       public String Name { get; set; }
  [Required(ErrorMessage = "User Name is Require")]
       public string UserName { get; set; }
  [Required(ErrorMessage = "City is Require")]
       [RegularExpression(@"^[a-zA-Z\s]+$", ErrorMessage = "City Field Accept Only Alphabet...")]
       public String City { get; set; }
       [Required(ErrorMessage = "Gender is Require")]
       [RegularExpression(@"^[a-zA-Z\s]+$", ErrorMessage = "Enter Correct Gender...")]
       public String Gender { get; set; }
       [Required(ErrorMessage = "Age Must be 18 to 55")]
       [Range(18, 55)]
       public int Age { get; set; }
       [Required]
       [RegularExpression(@"^[0-9]{10}", ErrorMessage = "Mobile Number Must be 10 Charector")]
       public String Mobile { get; set; }
       [Required]
       [RegularExpression(@"^([a-zA-Z0-9@#$%^&+=*]{6,10})$", ErrorMessage = "Minimum password length is 6")]
       public string Password { get; set; }
       [Required]
       public int Salary { get; set; }
  [Required]
       public int DesignationId { get; set; }
  public Designation Designation { get; set; }
   }
 
   public class UserContext : DbContext
   {
       public UserContext()
            : base("name=UserEntity")
       {
       }
       public DbSet<User> Users { get; set; }
       public DbSet<Designation> Designations { get; set; }
   }
}


And add the following action methods in the Controller class:

using MvcApplication2.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Text;
namespace MvcApplication2.Controllers
{
   public class AccountController : Controller
   {
       UserContext db = new UserContext();
  public ActionResult Login()
       {
            if(Request.IsAuthenticated)
            {
                  return RedirectToAction("Index", "Home");
            }
            return View();
       }
      [HttpPost]
       public ActionResult Login(User model)
       {
        User data = db.Users.FirstOrDefault(x => x.UserName == model.UserName && x.Password == model.Password);
            if(data != null)
            {
             FormsAuthentication.SetAuthCookie(data.UserName,false);
                return RedirectToAction("Index", "Home");
            }
            ViewBag.Error = "Invalid user name or password!!";
            return View();
 }
 
        public ActionResult Logout()
       {
            FormsAuthentication.SignOut();
            return RedirectToAction("Login");
       }
 
public ActionResult SignUp()
       {
            ViewBag.DesignationId = new SelectList(db.Designations, "DesignationId", "Name");
            int?maxId = db.Users.Max(x => (int?)x.Id) + 1;
  ViewData["maxId"] = maxId ?? 1;
  return View();
       }
       [HttpPost]
       public ActionResult SignUp(User model)
       {
            if(ModelState.IsValid)
            {
                db.Users.Add(model);
                db.SaveChanges();
                return RedirectToAction("Login");
            }
            ViewBag.DesignationId = new SelectList(db.Designations, "Id", "Name", model.DesignationId);
            return View(model);
 
 
        }
   }
}

Add the View for above methods in the Controller class:

Login View:
@model MvcApplication2.Models.User
@{
   ViewBag.Title = "Index";
}
<div class="container">
   <div class="col-md-6 col-md-offset-3 well"style="margin-top: 80px">
       @using (Html.BeginForm("Login", "Account", FormMethod.Post))
       {
            <h2 class="text-center">Login Page</h2>
            <br />
            <div class="text-danger">
                @ViewBag.Error
            </div>
            <div class="form-group">
                @Html.TextBoxFor(model => model.UserName, new { placeholder = "User Name", @class = "form-control" })
            </div>
            <div class="form-group">
                @Html.PasswordFor(model => model.Password, new { placeholder = "Password", @class = "form-control" })
            </div>
            <br />
            <div class="align-center">
                <button type="submit" class="btn btn-default" id="login">Login</button>
            </div>
       }
   </div>
 </div>

Sign Up View:
@model MvcApplication2.Models.User
@{
   ViewBag.Title = "Home";
}
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<style>
    .small-top {margin-top: 10px;}
  .myvalidation {color: red;}
</style>
<div class="container">
 <div class="col-md-8 col-md-offset-2">
        @using (Html.BeginForm("SignUp", "Account", FormMethod.Post))
       {        @Html.ValidationSummary(false, "", new { @class = "myvalidation" })
           
            <div class=" row small-top">
                <div class="col-md-3">
                    @Html.LabelFor(model =>model.Id)
                </div>
                <div class="col-md-9">
                    @Html.TextBox("Id", ViewData["maxId"], new { @class = "form-control", @readonly = "readonly" })
                </div>
            </div>
          <div class=" row small-top">
                <div class="col-md-3">
                    @Html.LabelFor(model =>model.Name)
                </div>
                <divclass="col-md-9">
                   @Html.TextBoxFor(model =>model.Name, new { @class = "form-control" })
                </div>
            </div>
            <div class=" row small-top">
                <div class="col-md-3">
                    @Html.LabelFor(model =>model.UserName)
                </div>
                <div class="col-md-9">
                    @Html.TextBoxFor(model =>model.UserName, new { @class = "form-control" })
                </div>
            </div>             <div class=" row small-top">
                <div class="col-md-3">
                    @Html.LabelFor(model =>model.City)
                </div>
                <divclass="col-md-9">
                    @Html.TextBoxFor(model =>model.City, new { @class = "form-control" })
                </div>
            </div>
            <div class=" row small-top">
                <div class="col-md-3">
                    @Html.LabelFor(model =>model.Gender)
                </div>
                <divclass="col-md-9">
                    @Html.DropDownList("Gender", new List<SelectListItem>
                 {
                    new SelectListItem{Text="Male",    Value="Male"},
                    new SelectListItem{Text="Female",Value = "Female" }, "--Select Gender--",new { @class = "form-control" })
                </div>
            </div>
      
            <div class=" row small-top">
                <div class="col-md-3">
                    @Html.LabelFor(model =>model.Age)
                </div>
                <div lass="col-md-9">
                    @Html.TextBoxFor(model =>model.Age, new { @class = "form-control" })
                </div>
            </div>
                   <div class=" row small-top">
                <div class="col-md-3">
                    @Html.LabelFor(model =>model.Mobile)
                </div>
                <div class="col-md-9">
                    @Html.TextBoxFor(model =>model.Mobile, new { @class = "form-control" })
    </div>
           </div>
           
            <div class=" row small-top">
                <div class="col-md-3">
                    @Html.LabelFor(model =>model.Password)
                </div>
                <div lass="col-md-9">
                    @Html.TextBoxFor(model =>model.Password, new { @class = "form-control" })
                </div>
            </div>
            <div class=" row small-top">
                <div class="col-md-3">
                    @Html.LabelFor(model =>model.Salary)
                </div>
                <div class="col-md-9">
                    @Html.TextBoxFor(model =>model.Salary, new { @class = "form-control" })
                </div>
            </div>
        
            <div class=" row small-top">
                <div class="col-md-3">
                    @Html.LabelFor(model =>model.DesignationId, "Designation")
                </div>
                <div class="col-md-9">
                    @Html.DropDownList("DesignationId", "--Select Designation--")
                </div>
            </div>
            <div class=" row small-top">
                <div class="col-md-12 text-center">
                    <input type="submit" value="Add" class="btn btn-info" />
               </div>
            </div>
       }
    </div> 
</div>

Now, Create a Shared folder on Views folder and add a view _Layout.cshtml.

_Layout.cshtml:
<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width,initial-scale=1">
   <link href="~/Style/Site.css" rel="stylesheet" type="text/css" />
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
   <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.6/jquery.validate.unobtrusive.min.js"></script>
   <script src="https://cdn.jsdelivr.net/jquery.ajax.unobtrusive/3.2.4/jquery.unobtrusive-ajax.min.js"></script>
   <title>Home</title>
</head>
<body>
 <div class="container">
       <nav class="navbarnavbar-inverse">
            <div class="container-fluid">
                <divclass="navbar-header">
                    @if(User.Identity.IsAuthenticated)
                    {
                        <a class="navbar-brand" href="#">Welcome.. <b>@User.Identity.Name</b></a>
                    }
                </div>
                <ul class="nav navbar-nav navbar-right">
                     @if(!User.Identity.IsAuthenticated)
                    {
                        <li><a href="@Url.Action("SignUp", "Account")"><span class="glyphicon glyphicon-user"></span>Sign Up</a></li>
                    }
                    @if(User.Identity.IsAuthenticated)
                    {
                        <li><a href="@Url.Action("Logout", "Account")"><span class="glyphicon glyphicon-log-out"></span>&nbsp;&nbsp;Logout</a></li>
                    }
                    else if(!User.Identity.IsAuthenticated)
                    {
                        <li><a href="@Url.Action("Login", "Account")"><span class="glyphicon glyphicon-log-in"></span>&nbsp;Login</a></li>
                    }
                </ul>
            </div>
       </nav>
   </div>
 
   <div class="container">
       @RenderBody()
   </div>
   <div class="modal fade" id="divDialog" role="dialog">
       <div class="modal-dialog" style="width: 1150px;">
            <div class="modal-content">
                <div class="modal-header">
                    <div class="col-md-2" style="margin-left: 10px">
                        <label>Search By</label>
                    </div>
                     @using (Html.BeginForm("AllUserList", "Home", FormMethod.Post))
                    {       
                        <div class="col-md-2">
                         @Html.DropDownList("SearchBy", new List<SelectListItem>                 {
                    new SelectListItem{Text="Name", Value="Name", Selected=true},
                    new SelectListItem{Text="UserName", Value="UserName"},
                    new SelectListItem{Text="City", Value="City"},
                 }, new { @class = "form-control" })
 
                        </div>
                        <div class="col-md-2">
                            @Html.TextBox("Search", "", new { placeholder = "Search..", @class = "form-control" })
                        </div>
                        <div class="col-md-1">
                            <input type="submit" id="btnSubmit" value="Search" class="btn btn-success" />
                        </div>
                    }
 
                </div>
                <div class="modal-body">
                </div>
                <div class="modal-footer">
                    <div class="btn-group btn-group-justified" role="group" aria-label="group button">
                        <div class="btn-group" role="group">
                            <button type="button" class="btn btn-info close" data-dismiss="modal" role="button">Close</button>
                        </div>
                    </div>
                </div>
            </div>       </div>
   </div>
</body>
</html>

And outside of views you add a _ViewStart.cshtml view.

_ViewStart.cshtml:
@{
   Layout = "~/Views/Shared/_Layout.cshtml";
}

 

And now, add a controller “HomeController” with action method:


HomeController:
using System.Web;
using System.Web.Mvc;
using MvcApplication2.Models;
using System.Data.Entity;
using System.Data.SqlClient;
using System.Text;
namespace MvcApplication2.Controllers
{
   [Authorize]
   public class HomeController : Controller
   {
       UserContext db = new UserContext();
  public ActionResult Index()
       {
User data =db.Users.FirstOrDefault(x => x.UserName == User.Identity.Name);
            ViewBag.DesignationList = new SelectList(db.Designations, "DesignationId", "Name").ToList();
            return View(data);
       }
   }
}

And add view for Index method:
Index.cshtml:
<div class="container" id="cont">
   @if(User.Identity.IsAuthenticated)
     {
       <h1>Welcome.. <b>@User.Identity.Name</b></h1>
     }
</div>

 

After writing all codes if you are run the application then it look like this:

Login and Registration in ASP.Net MVC

When you click on Sign Up link then page are look like this:

Login and Registration in ASP.Net MVC

After inserting record in the Sign Up form when you click Add button then login page are open.

And after entering correct Username and password result are:

Login and Registration in ASP.Net MVC

Thank you.

  Modified On Jan-17-2018 12:36:24 AM

Leave Comment