You are currently viewing Create Registration and Login Web Page Using ASP.NET MVC for Beginner/ Student
Registration and Login Web Page Using ASP.NET MVC

Create Registration and Login Web Page Using ASP.NET MVC for Beginner/ Student

Create Registration and Login Web Page Using ASP.NET MVC for Beginner/ Student

Registration and Login are an important page for any web application. Registration and Login pages are also important as a point of interview practical for Beginner / Student. Design or Create Registration and Login Pages with ASP.NET MVC With Code First Approach is very easy. Please read this post up to end.

ASP.NET MVC Concept

MVC stands for Model, View and Controller. MVC separates the application into three components – Model, View and Controller.

Model: a Model is a class object used to pass data between View, Controller and to the database. Often, model objects retrieve and store model state in a database.

View: View is page used to display content over the website. View display application’s user interface (UI).

Controller: Controllers are the components that handle user interaction, work with the model, and ultimately select a view to render that displays UI.

Read more about ASP.NET MVC

Let’s Start with Model

In this Web application, we design Model for UserMaster, RegistrationModel and View Model SessionData to use session data in the entire website.

UserMaster.cs (in Models Folder)

public class UserMaster
    {
        [Key]
        public int User_id { get; set; }

        [DisplayName("First name")]
        public string User_firstname { get; set; }

        [DisplayName("Middle name")]
        public string User_middlename { get; set; }

        [DisplayName("Last name")]
        public string User_lastname { get; set; }

        [DisplayName("Contact")]
        public string User_contact { get; set; }

        [DisplayName("Date of Birth")]
        [DataType(DataType.Date)]
        public System.DateTime User_DOB { get; set; }

        [DisplayName("Address line1")]
        public string Company_address_line1 { get; set; }

        [DisplayName("Address line2")]
        public string Company_address_line2 { get; set; }

        [DisplayName("Email")]
        [EmailAddress(ErrorMessage ="Please enter a valid email")]
        public string User_email { get; set; }

        [DisplayName("City")]
        public string User_city { get; set; }

        [DisplayName("State")]
        public string User_state { get; set; }

        [DisplayName("Country")]
        public string User_country { get; set; }

        [DisplayName("Zipcode")]
        public string User_zipcode { get; set; }

        [DisplayName("Company id")]
        public int Company_Fk_Id { get; set; }

        [DisplayName("Role id")]
        public int Role_Fk_id { get; set; }

        [Required(ErrorMessage = "Please enter password")]
        [RegularExpression(@"^[a-zA-Z0-9\s]{8,15}$", ErrorMessage = "Please enter more than 8 character and special characters are not allowed")]
        [DataType(DataType.Password)]
        public String Password { get; set; }

        private DateTime _date = DateTime.Now;
        [DisplayName("Created Date")]
        public DateTime Create_date { get { return _date; } set { _date = value; } }



    }

RegistrationModel.cs (in Models Folder)

public class RegistrationModel
    {
        [Key]
        public int User_id { get; set; }
        [Required(ErrorMessage = "Please enter first name")]
        [DisplayName("First name")]
        public string User_firstname { get; set; }
        
        [DisplayName("Last name")]
        [Required(ErrorMessage = "Please enter last name")]
        public string User_lastname { get; set; }

        [DisplayName("Email")]
        [Required(ErrorMessage = "Please enter email")]
        [EmailAddress(ErrorMessage ="Please enter a valid email")]
        public string User_email { get; set; }
        
        [DisplayName("Company")]
        public int Company_Fk_Id { get; set; }

        [DisplayName("Role")]
        public int Role_Fk_id { get; set; }

        [Required(ErrorMessage = "Please enter password")]
        [DisplayName("Password")]
        [RegularExpression(@"^[a-zA-Z0-9\s]{8,15}$", ErrorMessage = "Please enter more than 8 character and special characters are not allowed")]
        [DataType(DataType.Password)]
        public String Password { get; set; }

        [Compare("Password", ErrorMessage = "Please confirm your password")]
        [DataType(DataType.Password)]
        [DisplayName("Confirm Password")]
        public String ConfirmPassword { get; set; }
        private DateTime _date = DateTime.Now;
        [DisplayName("Created Date")]
        public DateTime Create_date { get { return _date; } set { _date = value; } }

        
    }

Please note down in the registration model we have two fields for a password, one for password and on for confirm password while in the UserMaster we have only one field i.e password. There is no need to store Confirm password into the database. We pass the UserMaster Model object to the database to store registration details into the database.

Now create one view model for session data.

SessionData.cs (in ViewModels Folder)

public class SessionData
{
      public int UserId{get;set;}
      public string UserFname {get;set;}
      public string UserLname {get;set;}
      public string UserEmail {get;set;}
      public int CompanyId {get;set;}
}

Now Create Controller for Registration and Login page

RegistrationController.cs (in Controller Folder)

public class RegistrationController : Controller
    {

          private YourDatabase db = new YourDatabase();
        // GET: Registration
        public ActionResult Index()
        {
            return View();
        }

        // GET: Registration/Details/5
        public ActionResult Details(int id)
        {
            return View();
        }

        // GET: Registration/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Registration/Create
        [HttpPost]
        public ActionResult Create(RegistrationModel model)
        {                               
            UserMaster userMaster = new UserMaster();
            userMaster.User_id = model.User_id;
            userMaster.User_firstname = model.User_firstname;
            userMaster.User_lastname = model.User_lastname;
            userMaster.User_email = model.User_email;
            userMaster.Company_Fk_Id = model.Company_Fk_Id;
            userMaster.Role_Fk_id = model.Role_Fk_id;
            if(model.Password==model.ConfirmPassword)
            {
                userMaster.Password = model.Password;
            }
            //userMaster.Create_date = System.DateTime.Now;
            try
            {
                // TODO: Add insert logic here
                if (ModelState.IsValid)
                {
                    db.UserMasters.Add(userMaster);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
                return RedirectToAction("Index");
            }
            catch(Exception ex)
            {
                return View();
            }
        }

        // GET: Registration/Edit/5
        public ActionResult Edit(int id)
        {
            return View();
        }

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

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

        // GET: Registration/Delete/5
        public ActionResult Delete(int id)
        {
            return View();
        }

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

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

Please note that we compare password and confirm password before copy it into UserMaster object.

LoginController.cs (in Controller Folder)

public class LoginController : Controller
    {
        private YourDatabase = new YourDatabase();
        // GET: Login
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Index(LoginViewModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var userist = db.UserMasters.ToList();
                    var user = userist.FirstOrDefault(x => x.User_email == model.email && x.Password == model.password);
                    LogMaster logMaster = new LogMaster();
                    SessionData sData = new SessionData();
                    if (user != null)
                    {
                        ViewBag.UserName = user.User_firstname + " " + user.User_lastname;
                        sData.UserId = user.User_id;
                        sData.UserFname = user.User_firstname;
                        sData.UserLname = user.User_lastname;
                        sData.CompanyId = user.Company_Fk_Id;
                        sData.UserEmail = user.User_email;
                        Session["Logindata"] = sData;

                        logMaster.Log_Msg = "login by user into system ";
                        logMaster.User_Fk_id = user.User_id;
                        logMaster.Create_date = System.DateTime.Now;
                        db.LogMasters.Add(logMaster);
                        Session["Logindata"] = sData;
                        ViewBag.message = "Successful login";
                        db.SaveChanges();
                        return RedirectToAction("Index", "Admin");
                    }
                    else
                    {
                        ModelState.AddModelError("email", "Invalid login details");
                    }
                }
                catch(Exception e)
                {
                    ModelState.AddModelError("email", e.Message);
                }
            }
            return View();
        }

        //Get: Logout
        [Route("logout")]
        public ActionResult Logout()
        {
            Session.Clear();
            return RedirectToAction("Index", "Login");
        }
    }

Please note that the following practice is not a good way to get the login user details. This is only for example. need to find only one user details instead of all the users.

 var userist = db.UserMasters.ToList();
 var user = userist.FirstOrDefault(x => x.User_email == model.email && x.Password == model.password);

Now we design Layout /View for Registration and Login Page

Create.cshtml (in Views/Registration Folder)

@model YourApplicationName.Models.RegistrationModel

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
    ViewBag.Title = "Create Account";
}


<h2>Registration</h2>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")


@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
       
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.User_firstname, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.User_firstname, new { htmlAttributes = new { @class = "form-control",placeholder="First Name", Required = "true" } })
                @Html.ValidationMessageFor(model => model.User_firstname, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.User_lastname, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.User_lastname, new { htmlAttributes = new { @class = "form-control", placeholder = "Last Name", Required = "true" } })
                @Html.ValidationMessageFor(model => model.User_lastname, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.User_email, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.User_email, new { htmlAttributes = new { @class = "form-control", placeholder = "Email", Required = "true" } })
                @Html.ValidationMessageFor(model => model.User_email, "", new { @class = "text-danger" })
            </div>
        </div>



        <div class="form-group">
            @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control", placeholder = "Password", Required = "true" } })
                @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ConfirmPassword, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.ConfirmPassword, new { htmlAttributes = new { @class = "form-control", placeholder = "Confirm Password", Required = "true" } })
                @Html.ValidationMessageFor(model => model.ConfirmPassword, "", new { @class = "text-danger" })
            </div>
        </div>


        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create Account" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Login here", "Index","Login")
</div>

Index.cshtml (in Views/Login Folder)

@model YourApplicationName.ViewModels.LoginViewModel

@{
    ViewBag.Title = "Login";
}

<h2>Login</h2>


@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.email, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.email, new { htmlAttributes = new { @class = "form-control",placeholder="Email",Required="true" } })
                @Html.ValidationMessageFor(model => model.email, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.password, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.password, new { htmlAttributes = new { @class = "form-control", placeholder = "Password", Required = "true" } })
                @Html.ValidationMessageFor(model => model.password, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Login" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Create Account", "Create","Registration")
</div>

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

All Completed. You can run the application. Make sure you have created YourDatabase (Database Model Class Name) database object with Code First Approach. I will try to put another tutorial to create a database with the Code First Approach but until that time you can try this example at your end.

Hope this will help you.