Monday, 20 October 2014

Customized login sample in ASP.NET MVC4/5 using SQL Server 2012

Today's I am going to create a customized log in form in asp.net MVC4. This sample will help you to understand how to authenticate your users by using form authentication.
This sample cover following things:
1. Register a new user
2. Log in for registered users.
3. Log out after log in.
4. Use Linq to validate user.
5. Create table to store and validate users information.

  First of all create database (MVCSampleLogin) in SQL Server with  following tables.
1. Classes
ClassID int PK Auto increment by 1
Name varchar(50)

2. Users
UserID int PK Auto increment by 1
Username varchar(50)
Password varchar(50)
Email  varchar(500)
FirstName varchar(50)
Lastname varchar(50)
ClassID FK with Classes ID

Or I made this for you just run this query in your query window.
 create database [MVCSampleLogin]  
 USE [MVCSampleLogin]  
 GO  
 /****** Object: Table [dbo].[Classes]  Script Date: 16/09/2014 18:50:41 ******/  
 SET ANSI_NULLS ON  
 GO  
 SET QUOTED_IDENTIFIER ON  
 GO  
 SET ANSI_PADDING ON  
 GO  
 CREATE TABLE [dbo].[Classes](  
  [ClassID] [int] IDENTITY(1,1) NOT NULL,  
  [Name] [varchar](50) NULL,  
  CONSTRAINT [PK_Classes] PRIMARY KEY CLUSTERED   
 (  
  [ClassID] ASC  
 )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]  
 ) ON [PRIMARY]  
 GO  
 SET ANSI_PADDING OFF  
 GO  
 /****** Object: Table [dbo].[Users]  Script Date: 16/09/2014 18:50:42 ******/  
 SET ANSI_NULLS ON  
 GO  
 SET QUOTED_IDENTIFIER ON  
 GO  
 SET ANSI_PADDING ON  
 GO  
 CREATE TABLE [dbo].[Users](  
  [UserID] [int] IDENTITY(1,1) NOT NULL,  
  [Username] [varchar](50) NULL,  
  [Password] [varchar](50) NULL,  
  [Email] [varchar](500) NULL,  
  [FirstName] [varchar](50) NULL,  
  [Lastname] [varchar](50) NULL,  
  [ClassID] [int] NOT NULL,  
  CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED   
 (  
  [UserID] ASC  
 )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]  
 ) ON [PRIMARY]  
 GO  
 SET ANSI_PADDING OFF  
 GO  
 SET IDENTITY_INSERT [dbo].[Classes] ON   
 GO  
 INSERT [dbo].[Classes] ([ClassID], [Name]) VALUES (1, N'English')  
 GO  
 INSERT [dbo].[Classes] ([ClassID], [Name]) VALUES (2, N'Math')  
 GO  
 INSERT [dbo].[Classes] ([ClassID], [Name]) VALUES (3, N'SST')  
 GO  
 SET IDENTITY_INSERT [dbo].[Classes] OFF  
 GO  
 SET IDENTITY_INSERT [dbo].[Users] ON   
 GO  
 INSERT [dbo].[Users] ([UserID], [Username], [Password], [Email], [FirstName], [Lastname], [ClassID]) VALUES (1, N'Admin', N'123456', N'admin@gmail.com', N'admin', N'admin', 1)  
 GO  
 INSERT [dbo].[Users] ([UserID], [Username], [Password], [Email], [FirstName], [Lastname], [ClassID]) VALUES (2, N'ABC', N'123456', N'ac@gmail.com', N'abc', N'bec', 2)  
 GO  
 INSERT [dbo].[Users] ([UserID], [Username], [Password], [Email], [FirstName], [Lastname], [ClassID]) VALUES (3, N'rupin', N'new', N'rupindersingh456@ymail.com', N'rupinder', N'singh', 1)  
 GO  
 SET IDENTITY_INSERT [dbo].[Users] OFF  
 GO  
 ALTER TABLE [dbo].[Users] WITH CHECK ADD CONSTRAINT [FK_Users_Users] FOREIGN KEY([ClassID])  
 REFERENCES [dbo].[Classes] ([ClassID])  
 GO  
 ALTER TABLE [dbo].[Users] CHECK CONSTRAINT [FK_Users_Users]  
 GO  

Now your database has been created. Lets move to coding .

Create new project in visual studio

File > New > Project

Select MVC 4 Project and give a name MVCCustomLogin
 
Press  OK  and then select Basic Template from next window
Press OK,  It will take some time.
Now your basic project has been created. First of all create a home page:
Go to Solution Explorer > Controllers > Right Click > ADD > Controller
Click on Controller and give name Home.
Right click on action method and add view .


Click on Add button
This is your home page

Go to View > Shared > Layout.chtml

Write following code in layout page

 <!DOCTYPE html>  
 <html>  
 <head>  
   <meta charset="utf-8" />  
   <meta name="viewport" content="width=device-width" />  
   <title>@ViewBag.Title</title>  
 </head>  
 <body>  
   <div>  
     <div style="width: auto; background-color: #728ea7;">  
     @if (Request.IsAuthenticated) {  
       <strong>@Html.Encode(User.Identity.Name)</strong>  
       @Html.ActionLink("Sign Out", "Logout", "Accounts")  
     }  
     else {  
       @Html.ActionLink("Register", "Register", "Accounts")  
       <span> | </span>  
       @Html.ActionLink("Sign In", "Login", "Accounts")  
     }  
   </div>  
   @RenderBody()  
   </div>  
 </body>  
 </html>  
Click On Model and new ASP.NET Entity Data Model Click on generate from database and select MVCSampleLogin , then select both tables. (If you don't know please refer my first blog). Now create a new controller and give it name Accounts and paste this code here
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Web;  
 using System.Web.Mvc;  
 using SampleLoginMVC.Models;  
 using System.Web.Security;  
 namespace SampleLoginMVC.Controllers  
 {  
   public class AccountsController : Controller  
   {  
     //  
     // GET: /Accounts/  
     MVCSampleLoginEntities db = new MVCSampleLoginEntities();  
     //Show Register Controller  
     public ActionResult Register()  
     {  
       ViewBag.ClassID = new SelectList(db.Classes, "ClassID", "Name");  
       return View();  
     }  
     //Handle Register form post back  
     [HttpPost]  
     public ActionResult Register(User users)  
     {  
       // Check if state is valid  
       if (ModelState.IsValid)  
       {  
         //Save data in database  
         db.Users.Add(users);  
         db.SaveChanges();  
         return RedirectToAction("Index","Home");  
       }  
       ViewBag.ClassID = new SelectList(db.Classes, "ClassID", "Name");  
       return View();  
     }  
     [HttpGet]  
     public ActionResult Login()  
     {  
       //Show login page  
       return View();  
     }  
     [HttpPost]  
     public ActionResult Login(User user, bool RemberMe=false)  
     {  
       if (ModelState.IsValid)  
       {  
         //Get user from database where user name and password is match   
         var usr = db.Users.Where(x=>x.Username==user.Username && x.Password==user.Password).FirstOrDefault();  
         if (usr!=null)  
         {  
           //set user authCookies  
           FormsAuthentication.SetAuthCookie(user.Username, false);  
           //Redrect to Dashboard.  
           return RedirectToAction("Index", "Dashboard");  
         }  
         else  
         {  
           //Show error  
           ModelState.AddModelError("", "Login data is incorrect!");  
         }  
       }  
       return View(user);  
     }  
     public ActionResult Logout()  
     {  
       //Set Sign Out   
       FormsAuthentication.SignOut();  
       return RedirectToAction("Index", "Home");  
     }  
   }  
 }  
Add this line of code in web.config file

<authentication mode="Forms">

      <forms loginUrl="~/Account/Login" timeout="2880"></forms>

    </authentication>

Right click on register and add a view and add following code in this
 @model SampleLoginMVC.Models.User  
 @{  
   ViewBag.Title = "Register";  
 }  
 <h2>Register</h2>  
 @using (Html.BeginForm()) {  
   @Html.ValidationSummary(true)  
   <fieldset>  
     <legend>User</legend>  
     <div class="editor-label">  
       @Html.LabelFor(model => model.Username)  
     </div>  
     <div class="editor-field">  
       @Html.EditorFor(model => model.Username)  
       @Html.ValidationMessageFor(model => model.Username)  
     </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.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.FirstName)  
     </div>  
     <div class="editor-field">  
       @Html.EditorFor(model => model.FirstName)  
       @Html.ValidationMessageFor(model => model.FirstName)  
     </div>  
     <div class="editor-label">  
       @Html.LabelFor(model => model.Lastname)  
     </div>  
     <div class="editor-field">  
       @Html.EditorFor(model => model.Lastname)  
       @Html.ValidationMessageFor(model => model.Lastname)  
     </div>  
     <div class="editor-label">  
       @Html.LabelFor(model => model.ClassID)  
     </div>  
     <div class="editor-field">  
       @Html.DropDownList("ClassID", "Select")  
     </div>  
     <p>  
       <input type="submit" value="Create" />  
     </p>  
   </fieldset>  
 }  
Right click on Login action method in accounts controller and add login view ,paste folowing code
 @model SampleLoginMVC.Models.User  
 @{  
   ViewBag.Title = "Login";  
 }  
 <h2>Login</h2>  
 @using (Html.BeginForm()) {  
   @Html.ValidationSummary(true, "Login failed. Check your login details.");  
   <fieldset>  
     <legend>Login</legend>  
     <div class="editor-label">  
       @Html.LabelFor(model => model.Username)  
     </div>  
     <div class="editor-field">  
       @Html.EditorFor(model => model.Username)  
       @Html.ValidationMessageFor(model => model.Username)  
     </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>  
       <input type="checkbox" name="RemberMe" checked="checked" />  
     <p>  
       <input type="submit" value="Login" />  
     </p>  
   </fieldset>  
 }  
Add a new controller Dashboard and add index view, paste this code in dashboard/index view
 @{  
   ViewBag.Title = "Index";  
 }  
 <h2>Dashboard : After Login. </h2>  
Now your custom login is ready

1 comment :

  1. no click event work after i created the admin charisma template following your video, in the right side the element boxes do not collapse or expand on click of the buttons also accordion menu in the lefy nav bar does not expand, can you please tell me what i did wrong

    ReplyDelete