Writing A Sample Login Page In ASP.NET MVC

Login page is the basic need of any Application. The user information needs to be validated in the system before doing any action in the system.We will create a login form step by step.

Create a database named ConsumerBanking.

Create a table named CBLoginInfo

  1. create database ConsumerBanking  
  2.   
  3.  go  
  4.   
  5. USE [ConsumerBanking]  
  6. GO  
  7.   
  8. /****** Object:  Table [dbo].[CBLoginInfo]    Script Date: 8/7/2016 10:06:47 PM ******/  
  9. SET ANSI_NULLS ON  
  10. GO  
  11.   
  12. SET QUOTED_IDENTIFIER ON  
  13. GO  
  14.   
  15. CREATE TABLE [dbo].[CBLoginInfo](  
  16.     [CustomerId] [intNOT NULL,  
  17.     [UserName] [nvarchar](20) NULL,  
  18.     [Password] [nvarchar](20) NULL,  
  19.     [LastLoginDate] [datetime] NULL,  
  20.     [LoginFailedCount] [intNULL,  
  21.     [LoginIPAddress] [nvarchar](20) NULL,  
  22.     [CustomerTimeZone] [nvarchar](20) NULL,  
  23.     [LastAccessedDate] [datetime] NULL,  
  24.     [AccountLocked] [bitNULL,  
  25.  CONSTRAINT [PK_CBLogin1] PRIMARY KEY CLUSTERED   
  26. (  
  27.     [CustomerId] ASC  
  28. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  29. ON [PRIMARY]  
  30.   
  31. GO  

Note: Passwords are never stored in the plain text in any Application. It should be encrypted, so that no one can read it. For demonstration purposes, it is  plain text now.

Once some records are inserted into the SQL Server database, we will write a stored procedure to fetch the user information and validate the user information.

We will create a stored procedure, named GetCBLoginInfo.

There is the logic, which we will achieve in the stored procedure, as this logic is common in any login page.

  • If a user name and password is valid, it is a successful login and redirects the user to the landing page.
  • If a username does not exist in the database, it shows the error 'User Does not Exist'.
  • If the user is a valid user and wrong password is given by the user, it will give the message, number of failed attempts.
  • If failed attempt is more than or equal to 5 times, it will lock the user out.
  1. USE [ConsumerBanking]  
  2. GO  
  3. SET ANSI_NULLS ON  
  4. GO  
  5. SET QUOTED_IDENTIFIER ON  
  6. GO  
  7.   
  8. CREATE  PROCEDURE [dbo].[GetCBLoginInfo]  
  9.     @UserName VARCHAR(20),  
  10.     @Password varchar(20)  
  11. AS  
  12. SET NOCOUNT ON  
  13. Declare @Failedcount AS INT  
  14. SET @Failedcount = (SELECT LoginFailedCount from CBLoginInfo WHERE UserName = @UserName)  
  15.   
  16. IF EXISTS(SELECT * FROM CBLoginInfo WHERE UserName = @UserName)  
  17.   
  18.  BEGIN  
  19.   
  20.  IF EXISTS(SELECT * FROM CBLoginInfo WHERE UserName = @UserName AND Password = @Password )  
  21.     SELECT 'Success' AS UserExists  
  22. ELSE  
  23.   
  24. Update CBLoginInfo set  LoginFailedCount = @Failedcount+1  WHERE UserName = @UserName  
  25.   
  26. Update CBLoginInfo set LastLoginDate=GETDATE()  WHERE UserName = @UserName  
  27.  BEGIN  
  28. IF @Failedcount >=5  
  29.   
  30.   
  31. SELECT 'Maximum Attempt Reached (5 times) .Your Account is locked now.' AS UserExists  
  32. ELSE  
  33.   
  34. select CONVERT(varchar(10), (SELECT LoginFailedCount from CBLoginInfo   WHERE UserName = @UserName))   AS UserFailedcount  
  35. END   
  36. END  
  37.  ELSE  
  38.   
  39.  BEGIN   
  40.   
  41. SELECT 'User Does not Exists' AS UserExists  
  42.  END  

We have created the stored procedure. Our database part is ready now.

Now, we will create ASP.NET MVC Web Application to create a login page .We will call the stored procedure, using Entity framework to validate the user information from the database.

Create a new project and select ASP.NET Web Application. Click OK.

new
 
Select MVC and click OK.
 
mvc

The MVC project is created now.

We will use Entity Framework as a data fetching layer. We will add an EDMX file to fetch the data from the database. We will call the stored procedure, which we created earlier.

ado.net
 
Select the option Generate from the database.
 
Database
 
Select your database Server and the database tables in the next step.
 
 
connection
 
Select the stored procedure in the next step.
 
stored procedure 
 
Click Finish. Now, ADO.NET Entity Data Model is created for us. 
 
browser
 

We will create a new model class, named CBUserModel, which has two properties, named UserName and Password. This model class will be used to communicate between the view and controller. We have some basic validation to validate the user Name and the Password fields will not to be blank, using DataAnnotations from the System.ComponentModel.

  1. using System.ComponentModel.DataAnnotations;  
  2.   
  3. namespace CBLogin.Models  
  4. {  
  5.     public class CBUserModel  
  6.     {  
  7.         [Required(ErrorMessage = "UserName is required")]  
  8.         public string UserName { getset; }  
  9.         [Required(ErrorMessage = "Password is required")]  
  10.         [DataType(DataType.Password)]  
  11.         public string Password { getset; }  
  12.     }  
  13. }  
We will create a controller, named CBLoginController, which has the actions, given below:

The Index view will return us the Index view.

  1. public ActionResult Index()  
  2.       {  
  3.           return View();  
  4.       }  

This Index action with [Httppost] verb will be called, when the user posts the data after entering UserName and Password field. In this action, the Username and Password will be validated against the database.

  1. [HttpPost]  
  2. public ActionResult Index(CBUserModel model)  
  3. {  
  4.     ConsumerBankingEntities cbe = new ConsumerBankingEntities();  
  5.     var s = cbe.GetCBLoginInfo(model.UserName, model.Password);  
  6.   
  7.     var item = s.FirstOrDefault();  
  8.     if (item == "Success")  
  9.     {  
  10.   
  11.         return View("UserLandingView");  
  12.     }  
  13.     else if(item=="User Does not Exists")  
  14.   
  15.     {  
  16.         ViewBag.NotValidUser = item;  
  17.   
  18.     }  
  19.     else  
  20.     {  
  21.         ViewBag.Failedcount = item;  
  22.     }  
  23.   
  24.   return View("Index");  
  25. }  
The action UserLandingView will be called, when the user posts the data after entering UserName and Password field. There is a successful login. 
  1. public ActionResult UserLandingView()  
  2.     {  
  3.         return View();  
  4.     }  
Index View

In the Index view, we have two input textbox fields, named UserName, Password and a Login button.

  1. @model CBLogin.Models.CBUserModel  
  2.   
  3. <!DOCTYPE html>  
  4. <html lang="en">  
  5. <head>  
  6.     <meta charset="utf-8">  
  7.     <meta http-equiv="X-UA-Compatible" content="IE=edge">  
  8.     <meta name="viewport" content="width=device-width, initial-scale=1">  
  9.   
  10.     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">  
  11.     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css">  
  12.     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>  
  13.     <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>  
  14.     <style type="text/css">  
  15.         .bs-example {  
  16.             
  17.             height:220px;  
  18.               
  19.         }  
  20.   
  21.         .centerlook {  
  22.             padding-left: 400px;  
  23.             font-weight: bold;  
  24.             width: 1000px;  
  25.         }  
  26.         .error {  
  27.             padding-left: 400px;  
  28.             font-weight: bold;  
  29.             width: 1000px;  
  30.             color: red;  
  31.         }  
  32.   
  33.         .loginbtn {  
  34.             padding-left: 500px;  
  35.         }  
  36.     </style>  
  37.   
  38. </head>  
  39. <body>  
  40.   
  41.     @using (Html.BeginForm())  
  42.     {  
  43.         <div class="bs-example" style="border:2px solid gray;">  
  44.   
  45.             <div class="form-group centerlook">  
  46.                 <h1> Login </h1>  
  47.             </div>  
  48.             <div class="form-group centerlook">  
  49.                 <label>User Name: </label>  
  50.                @Html.EditorFor(model => model.UserName)*  
  51.                 @Html.ValidationMessageFor(model => model.UserName)  
  52.             </div>  
  53.             <div class="form-group centerlook">  
  54.                 <label>Password:</label>  
  55.                    @Html.EditorFor(model => model.Password) *  
  56.                 @Html.ValidationMessageFor(model => model.Password)  
  57.   
  58.             </div>  
  59.             <div class="form-group error">  
  60.                 @if (@ViewBag.Failedcount != null)  
  61.                 {  
  62.   
  63.                     <label> Failed Attempt count is: @ViewBag.Failedcount</label>  
  64.                 }  
  65.   
  66.                 @if (@ViewBag.NotValidUser != null)  
  67.                 {  
  68.   
  69.                     <label> @ViewBag.NotValidUser</label>  
  70.                 }  
  71.             </div>  
  72.             <div class="loginbtn">  
  73.   
  74.                 <input type="submit" value="Login" class="btn btn-primary" />  
  75.   
  76.             </div>  
  77.         </div>  
  78.     }  
  79. </body>  
  80. </html>   
When a user loads the Index action, the Index view will be loaded. When the user enters UserName, Password and clicks the Login button, the Index action with HttpPost attribute is called.

The Entity framework code validates the username and password, given below. Based on the status returned from the stored procedure, the user will be shown an error message or redirected to the landing page.

When we run the page, we get the output of the page, as we have stated in the starting of the topic.

 
Condition 1: If the User Name and Password is blank, it will show the Validation Error Message, as shown in the screen, given below. We can add regular expression and other validation with the help of Component Model .

login
 
Condition 2: If a User Name and Password is given by the user and UserName does not exist in the database /system, it shows message to the user “User Does not Exists”, as shown in the screen, given below:

login
 
 Condition 3: If the User Name and Password given by the user is a valid user and username and password is correct, the user will be navigated to the landing page view.
 
login

Condition 4: If the User Name and Password is given wrong for five times or more than five times, then the user account will be locked, as shown in the screen, given below:

login

 
Condition 5: If the User Name and Password is given wrong, the page will display the number of failed attempts done by the user . 

database
 
 We created a login page in ASP.NET MVC. I hope this will be useful. Thanks for reading.