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
- create database ConsumerBanking
- go
- USE [ConsumerBanking]
- GO
- /****** Object: Table [dbo].[CBLoginInfo] Script Date: 8/7/2016 10:06:47 PM ******/
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
- CREATE TABLE [dbo].[CBLoginInfo](
- [CustomerId] [int] NOT NULL,
- [UserName] [nvarchar](20) NULL,
- [Password] [nvarchar](20) NULL,
- [LastLoginDate] [datetime] NULL,
- [LoginFailedCount] [int] NULL,
- [LoginIPAddress] [nvarchar](20) NULL,
- [CustomerTimeZone] [nvarchar](20) NULL,
- [LastAccessedDate] [datetime] NULL,
- [AccountLocked] [bit] NULL,
- CONSTRAINT [PK_CBLogin1] PRIMARY KEY CLUSTERED
- (
- [CustomerId] 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
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.
- USE [ConsumerBanking]
- GO
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
- CREATE PROCEDURE [dbo].[GetCBLoginInfo]
- @UserName VARCHAR(20),
- @Password varchar(20)
- AS
- SET NOCOUNT ON
- Declare @Failedcount AS INT
- SET @Failedcount = (SELECT LoginFailedCount from CBLoginInfo WHERE UserName = @UserName)
- IF EXISTS(SELECT * FROM CBLoginInfo WHERE UserName = @UserName)
- BEGIN
- IF EXISTS(SELECT * FROM CBLoginInfo WHERE UserName = @UserName AND Password = @Password )
- SELECT 'Success' AS UserExists
- ELSE
- Update CBLoginInfo set LoginFailedCount = @Failedcount+1 WHERE UserName = @UserName
- Update CBLoginInfo set LastLoginDate=GETDATE() WHERE UserName = @UserName
- BEGIN
- IF @Failedcount >=5
- SELECT 'Maximum Attempt Reached (5 times) .Your Account is locked now.' AS UserExists
- ELSE
- select CONVERT(varchar(10), (SELECT LoginFailedCount from CBLoginInfo WHERE UserName = @UserName)) AS UserFailedcount
- END
- END
- ELSE
- BEGIN
- SELECT 'User Does not Exists' AS UserExists
- END
We have created the stored procedure. Our database part is ready now.
Create a new project and select ASP.NET Web Application. Click OK.


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.




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.
- using System.ComponentModel.DataAnnotations;
- namespace CBLogin.Models
- {
- public class CBUserModel
- {
- [Required(ErrorMessage = "UserName is required")]
- public string UserName { get; set; }
- [Required(ErrorMessage = "Password is required")]
- [DataType(DataType.Password)]
- public string Password { get; set; }
- }
- }
The Index view will return us the Index view.
- public ActionResult Index()
- {
- return View();
- }
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.
- [HttpPost]
- public ActionResult Index(CBUserModel model)
- {
- ConsumerBankingEntities cbe = new ConsumerBankingEntities();
- var s = cbe.GetCBLoginInfo(model.UserName, model.Password);
- var item = s.FirstOrDefault();
- if (item == "Success")
- {
- return View("UserLandingView");
- }
- else if(item=="User Does not Exists")
- {
- ViewBag.NotValidUser = item;
- }
- else
- {
- ViewBag.Failedcount = item;
- }
- return View("Index");
- }
- public ActionResult UserLandingView()
- {
- return View();
- }
In the Index view, we have two input textbox fields, named UserName, Password and a Login button.
- @model CBLogin.Models.CBUserModel
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="utf-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css">
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
- <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
- <style type="text/css">
- .bs-example {
- height:220px;
- }
- .centerlook {
- padding-left: 400px;
- font-weight: bold;
- width: 1000px;
- }
- .error {
- padding-left: 400px;
- font-weight: bold;
- width: 1000px;
- color: red;
- }
- .loginbtn {
- padding-left: 500px;
- }
- </style>
- </head>
- <body>
- @using (Html.BeginForm())
- {
- <div class="bs-example" style="border:2px solid gray;">
- <div class="form-group centerlook">
- <h1> Login </h1>
- </div>
- <div class="form-group centerlook">
- <label>User Name: </label>
- @Html.EditorFor(model => model.UserName)*
- @Html.ValidationMessageFor(model => model.UserName)
- </div>
- <div class="form-group centerlook">
- <label>Password:</label>
- @Html.EditorFor(model => model.Password) *
- @Html.ValidationMessageFor(model => model.Password)
- </div>
- <div class="form-group error">
- @if (@ViewBag.Failedcount != null)
- {
- <label> Failed Attempt count is: @ViewBag.Failedcount</label>
- }
- @if (@ViewBag.NotValidUser != null)
- {
- <label> @ViewBag.NotValidUser</label>
- }
- </div>
- <div class="loginbtn">
- <input type="submit" value="Login" class="btn btn-primary" />
- </div>
- </div>
- }
- </body>
- </html>
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 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:



swarnesh kumarPosted Nov 3, 2020, 10:16 PM
In this app what is the user id and password?
Azdev XxiPosted Nov 3, 2019, 7:38 PM
Thank for this article!
Pham VyPosted Mar 20, 2019, 1:39 AM
Thank for this article, I think add more constraint for column "LoginFailedCount" -- alter table CBLoginInfo ADD CONSTRAINT [DF_LoginFailedCount] DEFAULT ((0)) FOR [LoginFailedCount]
akshay shakyaPosted Aug 7, 2018, 5:00 AM
To much helpfull
Nagi reddy KandiPosted May 31, 2018, 8:57 AM
Pradeep Sahoo..You done four mistakes in Index.html.1)You kept * mark, need to remove it and Please replace UserName with Username
Nagi reddy KandiPosted May 31, 2018, 8:53 AM
Excellent Job.You connect with stored procedure is very good. But you didn't explain how to insert User Name and Password into Table.We can insert records manually.But your explanation is super............
dhara joshiPosted Mar 7, 2018, 5:49 AM
I have done same as this but i got compilation error like namespace could not be found
DyansmithPosted Oct 31, 2016, 3:00 AM
Nice post @ Pradeep Sahoo
SubashPosted Oct 23, 2016, 9:09 PM
Nice info
Manav PandyaPosted Oct 9, 2016, 3:15 AM
Great post ...
Ramesh PalaniappanPosted Aug 10, 2016, 10:20 AM
Nice Article.
Vignesh ManiPosted Aug 10, 2016, 8:33 AM
Nice
Humayun Kabir MamunPosted Aug 10, 2016, 6:17 AM
Nice...
Prasanna MuraliPosted Aug 9, 2016, 9:12 PM
Nice post...