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. go
  3. USE [ConsumerBanking]
  4. GO
  5. /****** Object: Table [dbo].[CBLoginInfo] Script Date: 8/7/2016 10:06:47 PM ******/
  6. SET ANSI_NULLS ON
  7. GO
  8. SET QUOTED_IDENTIFIER ON
  9. GO
  10. CREATE TABLE [dbo].[CBLoginInfo](
  11. [CustomerId] [int] NOT NULL,
  12. [UserName] [nvarchar](20) NULL,
  13. [Password] [nvarchar](20) NULL,
  14. [LastLoginDate] [datetime] NULL,
  15. [LoginFailedCount] [int] NULL,
  16. [LoginIPAddress] [nvarchar](20) NULL,
  17. [CustomerTimeZone] [nvarchar](20) NULL,
  18. [LastAccessedDate] [datetime] NULL,
  19. [AccountLocked] [bit] NULL,
  20. CONSTRAINT [PK_CBLogin1] PRIMARY KEY CLUSTERED
  21. (
  22. [CustomerId] ASC
  23. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  24. ) ON [PRIMARY]
  25. 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.

  1. USE [ConsumerBanking]
  2. GO
  3. SET ANSI_NULLS ON
  4. GO
  5. SET QUOTED_IDENTIFIER ON
  6. GO
  7. CREATE PROCEDURE [dbo].[GetCBLoginInfo]
  8. @UserName VARCHAR(20),
  9. @Password varchar(20)
  10. AS
  11. SET NOCOUNT ON
  12. Declare @Failedcount AS INT
  13. SET @Failedcount = (SELECT LoginFailedCount from CBLoginInfo WHERE UserName = @UserName)
  14. IF EXISTS(SELECT * FROM CBLoginInfo WHERE UserName = @UserName)
  15. BEGIN
  16. IF EXISTS(SELECT * FROM CBLoginInfo WHERE UserName = @UserName AND Password = @Password )
  17. SELECT 'Success' AS UserExists
  18. ELSE
  19. Update CBLoginInfo set LoginFailedCount = @Failedcount+1 WHERE UserName = @UserName
  20. Update CBLoginInfo set LastLoginDate=GETDATE() WHERE UserName = @UserName
  21. BEGIN
  22. IF @Failedcount >=5
  23. SELECT 'Maximum Attempt Reached (5 times) .Your Account is locked now.' AS UserExists
  24. ELSE
  25. select CONVERT(varchar(10), (SELECT LoginFailedCount from CBLoginInfo WHERE UserName = @UserName)) AS UserFailedcount
  26. END
  27. END
  28. ELSE
  29. BEGIN
  30. SELECT 'User Does not Exists' AS UserExists
  31. 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. namespace CBLogin.Models
  3. {
  4. public class CBUserModel
  5. {
  6. [Required(ErrorMessage = "UserName is required")]
  7. public string UserName { get; set; }
  8. [Required(ErrorMessage = "Password is required")]
  9. [DataType(DataType.Password)]
  10. public string Password { get; set; }
  11. }
  12. }
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. var item = s.FirstOrDefault();
  7. if (item == "Success")
  8. {
  9. return View("UserLandingView");
  10. }
  11. else if(item=="User Does not Exists")
  12. {
  13. ViewBag.NotValidUser = item;
  14. }
  15. else
  16. {
  17. ViewBag.Failedcount = item;
  18. }
  19. return View("Index");
  20. }
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. <!DOCTYPE html>
  3. <html lang="en">
  4. <head>
  5. <meta charset="utf-8">
  6. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  7. <meta name="viewport" content="width=device-width, initial-scale=1">
  8. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  9. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css">
  10. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  11. <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  12. <style type="text/css">
  13. .bs-example {
  14. height:220px;
  15. }
  16. .centerlook {
  17. padding-left: 400px;
  18. font-weight: bold;
  19. width: 1000px;
  20. }
  21. .error {
  22. padding-left: 400px;
  23. font-weight: bold;
  24. width: 1000px;
  25. color: red;
  26. }
  27. .loginbtn {
  28. padding-left: 500px;
  29. }
  30. </style>
  31. </head>
  32. <body>
  33. @using (Html.BeginForm())
  34. {
  35. <div class="bs-example" style="border:2px solid gray;">
  36. <div class="form-group centerlook">
  37. <h1> Login </h1>
  38. </div>
  39. <div class="form-group centerlook">
  40. <label>User Name: </label>
  41. @Html.EditorFor(model => model.UserName)*
  42. @Html.ValidationMessageFor(model => model.UserName)
  43. </div>
  44. <div class="form-group centerlook">
  45. <label>Password:</label>
  46. @Html.EditorFor(model => model.Password) *
  47. @Html.ValidationMessageFor(model => model.Password)
  48. </div>
  49. <div class="form-group error">
  50. @if (@ViewBag.Failedcount != null)
  51. {
  52. <label> Failed Attempt count is: @ViewBag.Failedcount</label>
  53. }
  54. @if (@ViewBag.NotValidUser != null)
  55. {
  56. <label> @ViewBag.NotValidUser</label>
  57. }
  58. </div>
  59. <div class="loginbtn">
  60. <input type="submit" value="Login" class="btn btn-primary" />
  61. </div>
  62. </div>
  63. }
  64. </body>
  65. </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.