Simple Register and Login application in MVC3 Razor with Database interaction

  • In this article we will create a simple project or application which demonstrates how to create simple register and login forms with database interaction.
  • We will use DataAnnotation to validate form input.
  • We will use EDMX and database first approach. In Database first approach, we first create our database and then update the EDMX with the entities.
  • We will create two forms. One for registering for application and other for login into the application.
  • We have divided the article into two parts. The database part shows the database structure and EDMX entities. The code part shows how to create forms and classes and how to save details.

Watch Video


Part 1

Part 2
Part 3
Part 4

Database :

We have created a Database named LoginTp. We have one table in our database to store User's register Details. We have named it as UserDetails. It looks like below :



In the table, UserId is our primary key and is identity(1,1). We are also storing user's firstname, lastname, dob, city, email and password.

We will update our EDMX with this database to create entities.
To see how to update EDMX from DB follow the link :


After updating EDMX or model from Database, our EDMX file looks like below :




The entity is created in the EDMX. We will use this EDMX to interact with the database.

Code :


We have divided the code part based on forms i.e. Register and Login. Lets start with Register Form.


Register :


ViewModel :


We have created a separate folder to hold our ViewModel. We have created a class file named Register.cs which holds properties to render on Register form. The class file looks as below :


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace Logintp.ViewModel
{
    public class Register
    {
        [Required]
        public string FirstName { get; set; }

        [Required]
        public string LastName { get; set; }

        [Required]
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}")]
        public DateTime DOB { get; set; }

        [Required]
        public string City { get; set; }

        [Required]
        public string Email { get; set; }

        [Required]
        [DataType(DataType.Password)]
        public string Password { get; set; }
    }
}

We have defined above properties to render on form. We have also used DataAnnotation attributes to validate the user's input. We have used Required attribute to make all the fields mandatory to answer. We have used DataType attribute to render input type = "password" for pasword property.

View :



@model Logintp.ViewModel.Register
@{
    ViewBag.Title = "Register";
    Layout = "../Shared/_Layout.cshtml";
    }

<h2>Register</h2>

<div style="color:Black;">@Html.ValidationSummary(true)</div>
<div>
@using(Html.BeginForm("SaveRegisterDetails","Register"))
{
@Html.EditorForModel("Register")
<input type="submit" value="Submit" />
}

</div>
@Html.ActionLink("Login","Login")
<script type="text/javascript">
    $(function () {
        $('#DOB').datepicker({
            onSelect: function (date, value) {
                debugger;
                $('#DOB').val(date);
            },
            dateFormat: 'dd/mm/yy'
        });
    });
</script>

We have used EditorForModel helper for rendering controls for properties defined in our Register ViewModel. We have created a button of type submit, which posts our form.
We have also used BeginForm helper to render form. We have passed two parameters, which are action name and controller name. The action specified in the controller will be called on posting the form. We have used jQuery DatePicker for DOB  property. This will render a datepicker on clicking the textbox rendered for DOB property.

Controller :




//This method is the first to call and renders the Register View.
        public ActionResult Register()
        {
            return View();
        }

        //The form's data in Register view is posted to this method. 
        //We have binded the Register View with Register ViewModel, so we can accept object of Register class as parameter.
        //This object contains all the values entered in the form by the user.
        [HttpPost]
        public ActionResult SaveRegisterDetails(Register registerDetails)
        {
            //We check if the model state is valid or not. We have used DataAnnotation attributes.
            //If any form value fails the DataAnnotation validation the model state becomes invalid.
            if (ModelState.IsValid)
            {
                //If the model state is valid i.e. the form values passed the validation then we are storing the User's details in DB.
                RegisterLogin reglog = new RegisterLogin();
                //Calling the SaveDetails method which saves the details.
                reglog.SaveDetails(registerDetails);
                ModelState.AddModelError("", "User Details Saved Successfully");
                return View("Register");
            }
            else
            {
                //If the validation fails, we are returning the model object with errors to the view, which will display the error messages.
                return View("Register",registerDetails);
            }
        }

The Register action method renders the Register View. The user fills the details and post the form. The form is posted to SaveRegisterDetails method. In this method we validates model state. If the model state is valid then the details are saved else user is displayed with error messages.

Service :


In this class we have wrote code to save the details. We have created a folder named Service which will hold the service classes. We have created a class named RegisterLogin. This class contains SaveDetails method. The class file looks like below.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Logintp.ViewModel;
using Logintp.Models;

namespace Logintp.Service
{
    public class RegisterLogin
    {
        //This method accepts object of Register ViewModel class.
        public void SaveDetails(Register register)
        {
            //Creating DataContext object.
            using (LoginTpEntities dataContext = new LoginTpEntities())
            {
                //Creating the UserDetails object which is our entity.
                UserDetails details = new UserDetails();
                details.FirstName = register.FirstName;
                details.LastName = register.LastName;
                details.UserName = register.Email;
                details.Password = register.Password;
                details.City = register.City;
                details.DOB = Convert.ToDateTime(register.DOB);
                //Saving the details.
                dataContext.UserDetails.AddObject(details);
                dataContext.SaveChanges();
            }
        }
    }
}

The service class contains the method or code to save the user details. This we can consider the DataAccess layer as well.
Till this point we have saved the user details. We are done with Register Form. We will see Login form below.


Login :

ViewModel :

public class LoginViewModel
    {
        [Required]
        public string Username { get; set; }

        [Required]
        [DataType(DataType.Password)]
        public string Password { get; set; }
    }

We have created a ViewModel for Login form. We have include two properties.

View :



@model Logintp.ViewModel.LoginViewModel
@{
    ViewBag.Title = "Login";
    Layout = "../Shared/_Layout.cshtml";
}

<h2>Login</h2>

<div style="color:Black;">@Html.ValidationSummary(true)</div>
<div>
@using(Html.BeginForm())
{
@Html.EditorForModel("LoginViewModel")
<input type="submit" value="Login" />
}

</div>

We have used EditorForModel helper again to render controls for the properties in LoginViewmodel. We are posting the form on click of login button.

Controller :

     //This action method renders the Login View.
        public ActionResult Login()
        {
            return View();
        }

        //The login form is posted to this method.
        [HttpPost]
        public ActionResult Login(LoginViewModel model)
        {
            //Checking the state of model passed as parameter.
            if (ModelState.IsValid)
            {
                RegisterLogin login = new RegisterLogin();
                //Validating the user, whether the user is valid or not.
                bool isValidUser = login.IsValidUser(model);
                //If user is valid we are redirecting it to Welcome page.
                if (isValidUser)
                    return View("Welcome");
                else
                {
                    //If the username and password combination is not present in DB then error message is shown.
                    ModelState.AddModelError("Failure", "Wrong Username and password combination !");
                    return View();
                }
            }
            else
            {
                //If model state is not valid, the model with error message is returned to the View.
                return View(model);
            }
        }

        public ActionResult Welcome()
        {
            return View();
        }

The first action method renders the Login form. The login form on submit is posted to the Login Action method. In this method we check the user with username and password combination entered on the login form in DB. If the match is found then user is redircted to Welcome page else error message is shown.

Service :



public bool IsValidUser(LoginViewModel model)
        {
            using (LoginTpEntities dataContext = new LoginTpEntities())
            {
                //Retireving the user details from DB based on username and password enetered by user.
                UserDetails user = dataContext.UserDetails.Where(query => query.UserName.Equals(model.Username) && query.Password.Equals(model.Password)).SingleOrDefault();
                //If user is present, then true is returned.
                if (user == null)
                    return false;
                    //If user is not present false is returned.
                else
                    return true;
            }
        }

The above method validates the presence of username and password combination in database and returns bool value accordingly.

Layout :



<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery-1.8.3.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.ui.datepicker.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.ui.widget.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.ui.core.min.js")" type="text/javascript"></script>
    <link href="@Url.Content("~/Content/themes/base/jquery.ui.all.css")" rel="stylesheet" type="text/css" />
</head>

<body>
    @RenderBody()
</body>
</html>

The above is the Layout used. We have added jQuery references for above files to work with jQuery DatePicker.

Snapshots :


Register Form :




Register Form With errors :


Login Form :


Login Form with unmatched Username and Password :




Database Details :




Must Read:

Validate Form using Data Annotation

12 comments:

  1. Its Nice Blog for newly started Mvc learning People








    ReplyDelete
  2. This comment has been removed by a blog administrator.

    ReplyDelete
  3. i have followed all the steps, it is showing the login form but after clicking the login button nothing happens

    ReplyDelete
    Replies
    1. Can you mail me your solution at 20fingers2brains@gmail.com.

      Delete
    2. will you please send me the Source code my email id is sajid@sajid.info

      Delete
  4. Please send the code for edit and delete also..

    ReplyDelete
  5. Please send me the source code to pmohana106@gmail.com, register is working but login is not working.

    ReplyDelete
  6. its nice article But I am searching for one thing more in this article. I searched alot on internet but I am unable to find the answer that how can i authenticate and authorize user using this code.

    It will be appreciated that if you add authentication and authorization in this article too..

    Thanks

    ReplyDelete
  7. Plz send me the source code
    deepthicj1@gmail.com

    ReplyDelete
  8. sir you have to create Simple Register and Login application in MVC3 Razor with Database interaction
    My question is how to create Simple Register and Login application in MVC4 Razor with Database interaction
    same process using mvc4

    ReplyDelete
  9. it is a good article..I am a beginner in MVC..It help me a lot.Thank you so much..

    ReplyDelete