articles

Home / DeveloperSection / Articles / Login and Registration in ASP.Net MVC

Login and Registration in ASP.Net MVC

Niraj Kumar Mishra6843 28-Aug-2017

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.


<authenticationmode="Forms">
      <formsname="Demo"loginUrl="~/Account/Login"protection="All"timeout="30"/>
    </authentication>
  <connectionStrings>
    <addname="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:



        publicstaticvoid 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
{
   publicclassDesignation
   {
 
       publicint DesignationId { get; set; }
       publicstring Name { get; set; }
  publicICollection<User> Users { get; set; }
  }
 
   publicpartialclassUser
   {
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.None)]
       publicint Id { get; set; }
       [Required(ErrorMessage = "Name is Require")]
       [RegularExpression(@"^[a-zA-Z\s]+$", ErrorMessage = "Name Field Accept Only Alphabet...")]
       publicString Name { get; set; }
  [Required(ErrorMessage = "User Name is Require")]
       publicstring UserName { get; set; }
  [Required(ErrorMessage = "City is Require")]
       [RegularExpression(@"^[a-zA-Z\s]+$", ErrorMessage = "City Field Accept Only Alphabet...")]
       publicString City { get; set; }
       [Required(ErrorMessage = "Gender is Require")]
       [RegularExpression(@"^[a-zA-Z\s]+$", ErrorMessage = "Enter Correct Gender...")]
       publicString Gender { get; set; }
       [Required(ErrorMessage = "Age Must be 18 to 55")]
       [Range(18, 55)]
       publicint Age { get; set; }
       [Required]
       [RegularExpression(@"^[0-9]{10}", ErrorMessage = "Mobile Number Must be 10 Charector")]
       publicString Mobile { get; set; }
       [Required]
       [RegularExpression(@"^([a-zA-Z0-9@#$%^&+=*]{6,10})$", ErrorMessage = "Minimum password length is 6")]
       publicstring Password { get; set; }
       [Required]
       publicint Salary { get; set; }
  [Required]
       publicint DesignationId { get; set; }
  publicDesignation Designation { get; set; }
   }
 
   publicclassUserContext : DbContext
   {
       public UserContext()
            : base("name=UserEntity")
       {
       }
       publicDbSet<User> Users { get; set; }
       publicDbSet<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
{
   publicclassAccountController : Controller
   {
       UserContext db = newUserContext();
  publicActionResult Login()
       {
            if(Request.IsAuthenticated)
            {
                  return RedirectToAction("Index", "Home");
            }
            return View();
       }
      [HttpPost]
       publicActionResult 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();
 }
 
        publicActionResult Logout()
       {
            FormsAuthentication.SignOut();
            return RedirectToAction("Login");
       }
 
publicActionResult SignUp()
       {
            ViewBag.DesignationId = newSelectList(db.Designations, "DesignationId", "Name");
            int?maxId = db.Users.Max(x => (int?)x.Id) + 1;
  ViewData["maxId"] = maxId ?? 1;
  return View();
       }
       [HttpPost]
       publicActionResult SignUp(User model)
       {
            if(ModelState.IsValid)
            {
                db.Users.Add(model);
                db.SaveChanges();
                return RedirectToAction("Login");
            }
            ViewBag.DesignationId = newSelectList(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";
}
<divclass="container">
   <divclass="col-md-6 col-md-offset-3 well"style="margin-top: 80px">
       @using (Html.BeginForm("Login", "Account", FormMethod.Post))
       {
            <h2class="text-center">Login Page</h2>
            <br/>
            <divclass="text-danger">
                @ViewBag.Error
            </div>
            <divclass="form-group">
                @Html.TextBoxFor(model => model.UserName, new { placeholder = "User Name", @class = "form-control" })
            </div>
            <divclass="form-group">
                @Html.PasswordFor(model => model.Password, new { placeholder = "Password", @class = "form-control" })
            </div>
            <br/>
            <divclass="align-center">
                <buttontype="submit"class="btn btn-default"id="login">Login</button>
            </div>
       }
   </div>
 </div>

Sign Up View:
@model MvcApplication2.Models.User
@{
   ViewBag.Title = "Home";
}
<scriptsrc="~/Scripts/jquery-1.7.1.min.js"></script>
<scriptsrc="~/Scripts/jquery.validate.min.js"></script>
<scriptsrc="~/Scripts/jquery.validate.unobtrusive.js"></script>
<style>
    .small-top {margin-top: 10px;}
  .myvalidation {color: red;}
</style>
<divclass="container">
 <divclass="col-md-8 col-md-offset-2">
        @using (Html.BeginForm("SignUp", "Account", FormMethod.Post))
       {        @Html.ValidationSummary(false, "", new { @class = "myvalidation" })
           
            <divclass=" row small-top">
                <divclass="col-md-3">
                    @Html.LabelFor(model =>model.Id)
                </div>
                <divclass="col-md-9">
                    @Html.TextBox("Id", ViewData["maxId"], new { @class = "form-control", @readonly = "readonly" })
                </div>
            </div>
          <divclass=" row small-top">
                <divclass="col-md-3">
                    @Html.LabelFor(model =>model.Name)
                </div>
                <divclass="col-md-9">
                   @Html.TextBoxFor(model =>model.Name, new { @class = "form-control" })
                </div>
            </div>
            <divclass=" row small-top">
                <divclass="col-md-3">
                    @Html.LabelFor(model =>model.UserName)
                </div>
                <divclass="col-md-9">
                    @Html.TextBoxFor(model =>model.UserName, new { @class = "form-control" })
                </div>
            </div>            <divclass=" row small-top">
                <divclass="col-md-3">
                    @Html.LabelFor(model =>model.City)
                </div>
                <divclass="col-md-9">
                    @Html.TextBoxFor(model =>model.City, new { @class = "form-control" })
                </div>
            </div>
            <divclass=" row small-top">
                <divclass="col-md-3">
                    @Html.LabelFor(model =>model.Gender)
                </div>
                <divclass="col-md-9">
                    @Html.DropDownList("Gender", newList<SelectListItem>
                 {
                    newSelectListItem{Text="Male",    Value="Male"},
                    newSelectListItem{Text="Female",Value = "Female" }, "--Select Gender--",new { @class = "form-control" })
                </div>
            </div>
      
            <divclass=" row small-top">
                <divclass="col-md-3">
                    @Html.LabelFor(model =>model.Age)
                </div>
                <divlass="col-md-9">
                    @Html.TextBoxFor(model =>model.Age, new { @class = "form-control" })
                </div>
            </div>
                   <divclass=" row small-top">
                <divclass="col-md-3">
                    @Html.LabelFor(model =>model.Mobile)
                </div>
                <divclass="col-md-9">
                    @Html.TextBoxFor(model =>model.Mobile, new { @class = "form-control" })
    </div>
           </div>
           
            <divclass=" row small-top">
                <divclass="col-md-3">
                    @Html.LabelFor(model =>model.Password)
                </div>
                <divlass="col-md-9">
                    @Html.TextBoxFor(model =>model.Password, new { @class = "form-control" })
                </div>
            </div>
            <divclass=" row small-top">
                <divclass="col-md-3">
                    @Html.LabelFor(model =>model.Salary)
                </div>
                <divclass="col-md-9">
                    @Html.TextBoxFor(model =>model.Salary, new { @class = "form-control" })
                </div>
            </div>
        
            <divclass=" row small-top">
                <divclass="col-md-3">
                    @Html.LabelFor(model =>model.DesignationId, "Designation")
                </div>
                <div class="col-md-9">
                    @Html.DropDownList("DesignationId", "--Select Designation--")
                </div>
            </div>
            <divclass=" row small-top">
                <divclass="col-md-12 text-center">
                    <inputtype="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:
<!DOCTYPEhtml>
<html>
<head>
   <metacharset="utf-8">
   <metaname="viewport"content="width=device-width,initial-scale=1">
   <linkhref="~/Style/Site.css"rel="stylesheet"type="text/css"/>
   <linkrel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
   <scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
   <scriptsrc="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
   <scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
   <scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.6/jquery.validate.unobtrusive.min.js"></script>
   <scriptsrc="https://cdn.jsdelivr.net/jquery.ajax.unobtrusive/3.2.4/jquery.unobtrusive-ajax.min.js"></script>
   <title>Home</title>
</head>
<body>
 <divclass="container">
       <navclass="navbarnavbar-inverse">
            <divclass="container-fluid">
                <divclass="navbar-header">
                    @if(User.Identity.IsAuthenticated)
                    {
                        <aclass="navbar-brand"href="#">Welcome.. <b>@User.Identity.Name</b></a>
                    }
                </div>
                <ulclass="nav navbar-nav navbar-right">
                     @if(!User.Identity.IsAuthenticated)
                    {
                        <li><ahref="@Url.Action("SignUp", "Account")"><spanclass="glyphicon glyphicon-user"></span>Sign Up</a></li>
                    }
                    @if(User.Identity.IsAuthenticated)
                    {
                        <li><ahref="@Url.Action("Logout", "Account")"><spanclass="glyphicon glyphicon-log-out"></span>&nbsp;&nbsp;Logout</a></li>
                    }
                    elseif(!User.Identity.IsAuthenticated)
                    {
                        <li><ahref="@Url.Action("Login", "Account")"><spanclass="glyphicon glyphicon-log-in"></span>&nbsp;Login</a></li>
                    }
                </ul>
            </div>
       </nav>
   </div>
 
   <divclass="container">
       @RenderBody()
   </div>
   <divclass="modal fade"id="divDialog"role="dialog">
       <divclass="modal-dialog"style="width: 1150px;">
            <divclass="modal-content">
                <divclass="modal-header">
                    <divclass="col-md-2"style="margin-left: 10px">
                        <label>Search By</label>
                    </div>
                     @using (Html.BeginForm("AllUserList", "Home", FormMethod.Post))
                    {       
                        <divclass="col-md-2">
                         @Html.DropDownList("SearchBy", newList<SelectListItem>                 {
                    newSelectListItem{Text="Name", Value="Name", Selected=true},
                    newSelectListItem{Text="UserName", Value="UserName"},
                    newSelectListItem{Text="City", Value="City"},
                 }, new { @class = "form-control" })
 
                        </div>
                        <divclass="col-md-2">
                            @Html.TextBox("Search", "", new { placeholder = "Search..", @class = "form-control" })
                        </div>
                        <divclass="col-md-1">
                            <inputtype="submit"id="btnSubmit"value="Search"class="btn btn-success"/>
                        </div>
                    }
 
                </div>
                <divclass="modal-body">
                </div>
                <divclass="modal-footer">
                    <divclass="btn-group btn-group-justified"role="group"aria-label="group button">
                        <divclass="btn-group"role="group">
                            <buttontype="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]
   publicclassHomeController : Controller
   {
       UserContext db = newUserContext();
  publicActionResult Index()
       {
User data =db.Users.FirstOrDefault(x => x.UserName == User.Identity.Name);
            ViewBag.DesignationList = newSelectList(db.Designations, "DesignationId", "Name").ToList();
            return View(data);
       }
   }
}

And add view for Index method:
Index.cshtml:
<divclass="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 onSign 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.


Updated 12-Jul-2020

Leave Comment

Comments

Liked By