Custom User Login and Registration Page in ASP.Net MVC3 with Razor and Entity Framework

Description:

In this article I will demonstrate a sample project showing how to create a Login and Registration Page using ASP.Net MVC3 Razor and Entity Framework.

Content:

Here my scenario is that an employee of a company can register his details with a registration form and later he can login thorough his user credentials for doing his required tasks.

First create a new ASP.Net MVC3 project and give the Project name "CabAutomationSystem".

asp1.gif

Then go to the "Site.css" folder under the content folder and paste the two code segments shown below to replace the original below this two code content.

asp2.gif

/*----------------------------------------------------------
The base color for this template is #5c87b2. If you'd like
to use a different color start by replacing all instances of
#5c87b2 with your new color.
----------------------------------------------------------*/
body
{
    background-color: #3399FF;
    font-size: 77%;
    font-family: Verdana, Tahoma, Arial, "Helvetica Neue" , Helvetica, Sans-Serif;
    margin: 0;
    padding: 0;
    color: #FFFFFF;
}

#main
{
    padding: 30px 30px 15px 30px;
    background-color: #999966;
    margin-bottom: 30px;
    _height: 1px;
    color: #2C2C2C;
    font-size: medium;
}


It will change the style and look of your website.

Then go to the Web config page for the main project and paste the code shown below for the connection string.

<add name="CabDBContext" connectionString="data source=.;Database=Cabdb;Trusted_Connection=true;" providerName="System.Data.SqlClient" />

asp3.gif

Now go to the "AccountController.cs" under the Controller folder and comment all the code.

In the same manner go to the "AccountModels.cs" under the Models folder and comment all the code.

Now it's time for creating the model class.

For that go to the Model Class and create two classes named "Employee" and "Cab".

Go to the Employee class and paste the code shown below.

asp4.gif

public class Employee
    {
        [Key]
        [ScaffoldColumn(false)]
        public int EmpId { get; set; }
        // [Required(ErrorMessage = "EmployeeName is required")]
       
//public string EmployeeName { get; set; }

        // [Required(ErrorMessage = "EmployeeID is required")]
        // public int EmployeeID { get; set; }
        [Required(ErrorMessage = "EmployeeName is required")]
        public string EmployeeName { get; set; }

        [Required(ErrorMessage = "EmployeeNo is required")]
        public int EmployeeNo { get; set; }

        [Required(ErrorMessage = "Email address is required")]
        [DataType(DataType.EmailAddress)]
        [Display(Name = "Email address")]
        public string Email { get; set; }

        [Required(ErrorMessage = "Pass word is required")]
        //[ValidatePasswordLength]
        [DataType(DataType.Password)]
        //[Display(Name = "Password")]
        public string Password { get; set; }

        ////[Required(ErrorMessage = "Confirm Password is required")]
        //[DataType(DataType.Password)]
        ////   [Display(Name = "Confirm password")]
        //[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
       
//public string ConfirmPassword { get; set; }

        [Required(ErrorMessage = "ProjectName is required")]
        public string ProjectName { get; set; }

        [Required(ErrorMessage = "Gender is required")]
        public string Gender { get; set; }

        #region m->1 Relation between Cab

        public int CabId { get; set; }

        public virtual Cab Cab { get; set; }
        #endregion
    }

Now go the Cab Class and paste the code shown below.

public class Cab
    {
        [ScaffoldColumn(false)]
        public int CabId { get; set; }
        public long BookId { get; set; }

        [Required(ErrorMessage = "BookTime is required")]
        public TimeSpan BookTime { get; set; }

       [Required(ErrorMessage = "JourneyTime is required")]
        public long JourneyTime { get; set; }

        [Required(ErrorMessage = "JourneyPlace is required")]
        public string JourneyPlace { get; set; }

        //public int TripId { get; set; }
       
//public virtual Trip Trip { get; set; }

        #region 1->m Relation between Cab and Emp
        public virtual List<Employee> Employee_List { get; set; }
        #endregion

    }

Now it's the time for creating the Object Class mapping by using the Entity Frawork.

For that You have to first take the add reference of "EntityFramework.dll". I will provide the dll in this project.

asp5.gif

Now create a folder name called "DatabaseContext" under the project and create a class named "CabDbContext.cs" file under that project. Now paste the code shown below in that class file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using CabAutomationSystem.Models;

namespace CabAutomationSystem.DatabaseContext
{
    public class CabDbContext : DbContext
    {
        public DbSet<Cab> Cab { get; set; }
        public DbSet<Employee> Employee { get; set; }
       
//public DbSet<Registration> Registration { get; set; }

    }
}


asp6.gif

Now go to the "_Layout.cshtml" file under the "Shared" folder and paste the code shown below.

<!DOCTYPE html>
<html>
<
head>
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script
>
</head>

<body>
    <div class="page">

        <div id="header">
            <div id="title">
                <h1>Taxi Cab Automation System</h1>
            </div
>

            <div id="logindisplay">
                @Html.Partial("_LogOnPartial")
            </div
>

            <div id="menucontainer">

                <ul id="menu">
                   @* <li>@Html.ActionLink("Home", "Index", "Home")</li>*@
                    @*<li>@Html.ActionLink("About", "About", "Home")</li>*@
                </ul
>

             </div>
        </div>
 
        <div id="main">
            @RenderBody()
            <div id="footer">
            </div>
        </div>
    </div
>
</body>
</
html>

Now go to the "HomeController.cs" file under the controller folder and replace the Index method with the code given below. And also create the object of "CAbdbContext" data object mapping class.

        // GET: /Home/
        CabDbContext _db = new CabDbContext();
        public ActionResult Index()
        {
            //ViewBag.Message = "Welcome to Login Page";
            //var v = ViewData.Model = _db.Employee.ToList();
            // return View(v);
            return View();
        }

The Index will be the home page of our application where it will show to give the Username and the Password and also the option for registering a new user.

Now go to the "Home" folder under the "View" folder and paste the code shown below under the "Index.cshtml" file after selectiong the all code.

@model CabAutomationSystem.Models.Employee
          
@{
    ViewBag.Title = "Log On";
}

<h2>Log On</h2>
<p>
    Please enter your username and password.
</p>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@Html.ValidationSummary(true, "Login was unsuccessful. Please correct the errors and try again.")

@using (Html.BeginForm()) {
    <div>
        <fieldset>
            <legend>Account Information</legend
>

       <div class="editor-label">
            @Html.LabelFor(model => model.Email)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Email)
            @Html.ValidationMessageFor(model => model.Email)
        </div
>

        <div class="editor-label">
            @Html.LabelFor(model => model.Password)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Password)
            @Html.ValidationMessageFor(model => model.Password)
        </div
>

            <p>
                <input type="submit" value="Log On" />..@Html.ActionLink("Register", "Create") if you don't have an account.
            </p>
        </fieldset>
    </div
>

Now run the code; it will look like:

asp7.gif

Now we have the Login Page. We don't yet have a page for new user registration.

For that go to the Home Controller and create a new action result method called "Create" for New Registration page.

The code for the "Create" method is:

public ActionResult Create()
        {
            ViewBag.Message = "Welcome to Login Page";
            var v = ViewData.Model = _db.Employee.ToList();
            var Employee = new Employee();

            return View(Employee);
        }
 
        //
       
// POST: /Home/Create

        [HttpPost]
        public ActionResult Create(Employee Employee)
        {
            try
            {

                // TODO: Add insert logic here
                if (ModelState.IsValid)
                {
 
                   
//Save Registration

                    _db.Employee.Add(Employee);
                    _db.SaveChanges();
 
                    return RedirectToAction("Index");

                }
 
                //return RedirectToAction("Index");
 
                //ViewBag.Route = _db.Cab.OrderBy(g => g.JourneyTime).ToList();
               // ViewBag.DropPoint = _db.Employee.OrderBy(a => a.EmployeeName).ToList();
                return View(Employee);
            }
            catch
            {
                return View();
            }
        }

Now the functionality of that Create method is that at first when there are no records and the user clicks the registration link button the "Create" action result will call the home controller and it will create the database as well as the "employee" and "cab" table from the "CabdbContext" entity framework class.

The complete code of the Home Controller is given below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CabAutomationSystem.DatabaseContext;
using CabAutomationSystem.Models;

namespace CabAutomationSystem.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        CabDbContext _db = new CabDbContext();
        public ActionResult Index()
        {
            //ViewBag.Message = "Welcome to Login Page";
            //var v = ViewData.Model = _db.Employee.ToList();
            // return View(v);
            return View();
        }
        public ActionResult About()
        {
            return View();
        }
        //
       
// GET: /Home/Details/5

        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /Home/Create
        public ActionResult Create()
        {
            ViewBag.Message = "Welcome to Login Page";
            var v = ViewData.Model = _db.Employee.ToList();
            var Employee = new Employee();
 
            return View(Employee);
        }

        //
       
// POST: /Home/Create

        [HttpPost]
        public ActionResult Create(Employee Employee)
        {
            try
            {

                // TODO: Add insert logic here
                if (ModelState.IsValid)
                {
 
                   
//Save Registration

                    _db.Employee.Add(Employee);
                    _db.SaveChanges();

                    return RedirectToAction("Index");

                }
 
               
//return RedirectToAction("Index");

                //ViewBag.Route = _db.Cab.OrderBy(g => g.JourneyTime).ToList();
               // ViewBag.DropPoint = _db.Employee.OrderBy(a => a.EmployeeName).ToList();
                return View(Employee);
            }
            catch
            {
                return View();
            }
       }

         //
       
// GET: /Home/Edit/5

        public ActionResult Edit(int id)
        {
            return View();
        }

        //
       
// POST: /Home/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
               
// TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
 
        //
       
// GET: /Home/Delete/5

        public ActionResult Delete(int id)
        {
            return View();
        }

        //
       
// POST: /Home/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
               
// TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}


Now we have to create the registration form.

For that go to the "Home" folder under the "Views" folder and add a new Razor file named "Create.cshtml". Paste the code shown below after selecting all the code.

@model CabAutomationSystem.Models.Employee 

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend> Fill Employee Details</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.EmployeeName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.EmployeeName)
            @Html.ValidationMessageFor(model => model.EmployeeName)
        </div
>

          <div class="editor-label">
            @Html.LabelFor(model => model.EmployeeNo )
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.EmployeeNo)
            @Html.ValidationMessageFor(model => model.EmployeeNo)
        </div>
         <div class="editor-label">
            @Html.LabelFor(model => model.Email) as UserName
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Email)
            @Html.ValidationMessageFor(model => model.Email)
        </div
>

       <div class="editor-label">
            @Html.LabelFor(model => model.Password)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Password)
            @Html.ValidationMessageFor(model => model.Password)
        </div>

       @*
  <div class="editor-label">
            @Html.LabelFor(model => model.ConfirmPassword)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ConfirmPassword)
            @Html.ValidationMessageFor(model => model.ConfirmPassword)
        </div>
*@

        <div class="editor-label">
            @Html.LabelFor(model => model.ProjectName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ProjectName)
            @Html.ValidationMessageFor(model => model.ProjectName)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Cab.JourneyPlace)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Cab.JourneyPlace)
            @Html.ValidationMessageFor(model => model.Cab.JourneyPlace)
        </div
>

        <div class="editor-label">
            @Html.LabelFor(model => model.Gender)
        </div>
        <div class="editor-field">
         @*    @Html.EditorFor(model => model.Gender)*@
            @Html.RadioButtonFor(model => model.Gender,"Male",true) Male  @Html.RadioButtonFor(model => model.Gender,"Female",false) Female
           @Html.ValidationMessageFor(model => model.Gender)<br
/>

        </div>

       @* <div class="editor-label">
            @Html.LabelFor(model => model.Cab.JourneyTime )
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Cab.JourneyTime)
            @Html.ValidationMessageFor(model => model.Cab.JourneyTime)
        </div>
*@
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

Now run the code; when you click the "Registration" link it will look like:

asp8.gif

Give the required data and press the Create button. It will automatically save the record to the database.

In my next article I will describe how to match the required username and password and redirect to a particular page for a given employee in the Log on information.


Similar Articles