Sunday 9 December 2012

Login Page in ASP.NET MVC 4 Razor

I will show you that how you can make your own login and register page in ASP.NET MVC 4 Razor.
Lets start by making a new project->ASP.NET MVC 4 web application->basic.

Step:-1: Create a model class User.cs in Models with two properties username and password.Here [Required] is data annotation which means that in database, we can't have such entry to be null.[Key] means that username is primary key to the database.
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace SampleLogin.Models
{
    public class User
    {
        [Required]
        [Key]
        public string Username { get; set; }
        [Required]
        public string Password { get; set; }
    }
}
Step:-2: Now, create a new class UserContext.cs which is derived from base class DbContext.cs .This class corresponds to the database in entity framework which has  elements of type Dbset<>.Here dataset corresponds to entity sets.Therefore, our UserContext class must have relation of type Dbset<User>.
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace SampleLogin.Models
{
    public class UserContext:DbContext
    {
        public DbSet Users { get; set; }
    }
}

Step:-3: Now, we have data classes ready.So, now make a new controller accountController.cs. Define a new action Register() in it.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace SampleLogin.Controllers
{
    public class accountController : Controller
    {
        //
        // GET: /account/
        public ActionResult Index()
        {
            return View();
        }

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

    }
}

Build the project to get intellisence for future.
Step:-4: Now add view to register with strongly typed model class User.cs. In view, we are using html helper to generate form, labels and textbox.

@model SampleLogin.Models.User
@{
    ViewBag.Title = "Register";
}

<h2>Register<h2>
@using (Html.BeginForm())
{
    @Html.Label("Username")
    @Html.TextBoxFor(m=>m.Username)

    @Html.Label("Password")
    @Html.PasswordFor(m=>m.Password)
    <input type="submit" value="Register">
    @Html.ValidationSummary()
}
Step:-5 Now, when we press submit button, the object User is passed to the controller.So , we have to define same action Register with parameter User and attribute [HttpPost] which means that this action will only be executed in case of Httppost .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SampleLogin.Models;

namespace SampleLogin.Controllers
{
    public class accountController : Controller
    {
        //
        // GET: /account/

        public ActionResult Index()
        {
            return View();
        }
        public ActionResult Register()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Register(User user)
        {
            using (UserContext db = new UserContext())
            {
                if (ModelState.IsValid)
                {
                    db.Users.Add(user);
                    db.SaveChanges();
                }
                else
                {
                    ModelState.AddModelError("","Some error has occured.");
                    View();
                }
            }
            return View();
        }
    }
}
Here we are initializing an instance of UserContext(i.e. database).Now, if model (or entity) is valid (or not having null values),then we are inserting it into the database.This is just a sample application , so, we are not encrypting password before inserting into database. But, in your real application, you need to encrypt it before inserting with "md5" or sha family. Step:-6:  Now, we have to create login action in account controller.For that create two login actions with one has no parameters and other has parameter "user" and of attribute [HttpPost].
public ActionResult Login()
{
    return View();
}
[HttpPost]
public ActionResult Login(User user)
{
    return View();
}
Add view to Login() wtih strongly typed model class "User.cs".And again use html helper to generate basic html form, textboxes and labels as we have done in register page.
@model SampleLogin.Models.User
@{
    ViewBag.Title = "Login";
}
<h2>Login</h2>
@using (Html.BeginForm())
{
    @Html.Label("Username")
    @Html.TextBoxFor(m=>m.Username)
    @Html.Label("Password")
    @Html.PasswordFor(m=>m.Password)
    <input type="submit" value="Login"/>
}
Step:-7: Now, change some code in login action of post type by the below code.Here, I am checking whether the password and username passed to database exists or not.If they exists , then we create cookies corresponding that username and redirect to Index page.
[HttpPost]
public ActionResult Login(User user)
{
     using (UserContext db = new UserContext())
     {
       try
       {
          if (ModelState.IsValid)
          {
            User us = db.Users.SingleOrDefault(m => m.Username == user.Username);
            if (us != null)
            {
               if (us.Password == user.Password)
               {
                  FormsAuthentication.SetAuthCookie(user.Username, false);
                  return RedirectToAction("Index");
               }
               ModelState.AddModelError("", "Invalid Username or Password");
               return View();
            }
            throw new ArgumentException("User doesn't exists");
        }
      }
      catch (ArgumentException e)
      {
             ModelState.AddModelError("",e.Message);
             return View();
      }
    }
    return View();
 }
In setting cookies, we set second parameter to be false, which means that cookie is not persistent in all sessions of browser.Second thing is that, I am just passing plain string for password in register and login action which is not correct.You can hash it , then can insert into the database. This is my first blog.Please comment below to improve the quality of blogs in future. Thanks for reading, hope that it is useful to you. You can download complete source from here

5 comments:

  1. Thanks for sharing useful information.I also refer some useful link about login form in asp.net mvc.

    http://www.loginseek.com/how-to-create-login-page-in-mvc3/

    https://www.mindstick.com/Blog/648/login-form-in-asp-dot-net-mvc-4

    ReplyDelete
  2. Hi, after implementing this i got the error. can you let me know what is mistake i have done.

    Error 1 'System.Data.Entity.DbSet' does not contain a definition for 'SingleOrDefault' and no extension method 'SingleOrDefault' accepting a first argument of type 'System.Data.Entity.DbSet' could be found (are you missing a using directive or an assembly reference?)

    ReplyDelete