In this article I will explain with an example, how to build a responsive (Mobile Friendly) User Login Form inside Bootstrap Modal Popup in ASP.Net using C# and VB.Net.
The responsive Login Form has been implemented using Custom ASP.Net Membership and Forms Authentication.
This article will also explains how to perform validations for the Bootstrap User Login Form using HTML5 required validation attribute.
It also has the Remember Me CheckBox feature which allows user to save the credentials when he visits site next time.
Complete source code is attached at the end of article.
 
 
Database
Responsive Login Form inside Bootstrap Modal Popup in ASP.Net
 
I am making use of the same database table Users which was used in the article Simple User Registration Form Example in ASP.Net.
 
Note: The SQL for creating the database is provided in the attached sample code.
 
 
Stored Procedure to Validate the User Credentials
The following stored procedure is used to validate the user credentials, this stored procedure first checks whether the username and password are correct else returns -1.
If the username and password are correct but the user has not been activated then the code returned is -2.
If the username and password are correct and the user account has been activated then UserId of the user is returned by the stored procedure.
CREATE PROCEDURE [dbo].[Validate_User]
      @Username NVARCHAR(20),
      @Password NVARCHAR(20)
AS
BEGIN
      SET NOCOUNT ON;
      DECLARE @UserId INT, @LastLoginDate DATETIME
     
      SELECT @UserId = UserId, @LastLoginDate = LastLoginDate
      FROM Users WHERE Username = @Username AND [Password] = @Password
     
      IF @UserId IS NOT NULL
      BEGIN
            IF NOT EXISTS(SELECT UserId FROM UserActivation WHERE UserId = @UserId)
            BEGIN
                  UPDATE Users
                  SET LastLoginDate = GETDATE()
                  WHERE UserId = @UserId
                  SELECT @UserId [UserId] -- User Valid
            END
            ELSE
            BEGIN
                  SELECT -2 -- User not activated.
            END
      END
      ELSE
      BEGIN
            SELECT -1 -- User invalid.
      END
END
 
 
Pages
This example consists of two pages Login page (Login.aspx) using which the user will login and the Landing page (Home.aspx) which is the page user will be redirected after successful authentication.
 
 
Login Page
This is the login form which will do the following:-
1. Authenticate user by verifying Username and Password.
2. Make sure user has activated his account. Refer my article for details Send user Confirmation email after Registration with Activation Link in ASP.Net.
3. If user is already logged in, he will be directly send to the Home page which is set as DefaultUrl in the FormsAuthentication setting of the Web.Config file.
 
 
HTML Markup
The HTML markup consists of an HTML Button and a DIV. The HTML Button will be used to open the HTML DIV as Bootstrap Modal Popup.
The HTML DIV consists two TextBoxes for Username and Password, a Button for submission, a CheckBox for the Remember Me feature, a Label for displaying the error message and lastly an additional Button to close the Bootstrap Modal Popup.
Note: Here the standard ASP.Net Login Form control is not used as it renders as HTML Table and hence cannot be responsive.
 
<script type="text/javascript" src='https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js'></script>
<script type="text/javascript" src='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/js/bootstrap.min.js'></script>
<link rel="stylesheet" href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/css/bootstrap.min.css'
    media="screen" />
<input type = "button" id="btnShowLogin" class="btn btn-primary" value = "Login" />
<script type="text/javascript">
    $(function () {
        $("#btnShowLogin").click(function () {
            $('#LoginModal').modal('show');
        });
    });
</script>
<form id="form1" runat="server">
<div class="modal fade" id="LoginModal" tabindex="-1" role="dialog" aria-labelledby="ModalTitle"
    aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                    &times;</button>
                <h4 class="modal-title" id="ModalTitle">
                    Login</h4>
            </div>
            <div class="modal-body">
                <label for="txtUsername">
                    Username</label>
                <asp:TextBox ID="txtUsername" runat="server" CssClass="form-control" placeholder="Enter Username"
                    required />
                <br />
                <label for="txtPassword">
                    Password</label>
                <asp:TextBox ID="txtPassword" runat="server" TextMode="Password" CssClass="form-control"
                    placeholder="Enter Password" required />
                <div class="checkbox">
                    <asp:CheckBox ID="chkRememberMe" Text="Remember Me" runat="server" />
                </div>
                <div id="dvMessage" runat="server" visible="false" class="alert alert-danger">
                    <strong>Error!</strong>
                    <asp:Label ID="lblMessage" runat="server" />
                </div>
            </div>
            <div class="modal-footer">
                <asp:Button ID="btnLogin" Text="Login" runat="server" OnClick="ValidateUser" Class="btn btn-primary" />
                <button type="button" class="btn btn-default" data-dismiss="modal">
                    Close</button>
            </div>
        </div>
    </div>
</div>
</form>
 
Responsive Login Form inside Bootstrap Modal Popup in ASP.Net
 
Both the TextBoxes have been specified with required attribute which is an HTML5 attribute for performing validations.
Responsive Login Form inside Bootstrap Modal Popup in ASP.Net
 
 
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.Security;
 
VB.Net
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Web.Security
 
 
Validating the User Credentials
The below event handler gets called when the Login button is clicked. Here the Username and Password entered by the user is passed to the stored procedure and its status is captured and if the value is not -1 (Username or password incorrect) or -2 (Account not activated) then a check is made for RedirectUrl in QueryString, if it exists then the user is redirected to value of the RedirectUrl and if it does not exists then the user is redirected to the Home page using FormsAuthentication RedirectFromLoginPage method.
C#
protected void ValidateUser(object sender, EventArgs e)
{
    string username = txtUsername.Text.Trim();
    string password = txtPassword.Text.Trim();
    int userId = 0;
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("Validate_User"))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@Username", username);
            cmd.Parameters.AddWithValue("@Password", password);
            cmd.Connection = con;
            con.Open();
            userId = Convert.ToInt32(cmd.ExecuteScalar());
            con.Close();
        }
        switch (userId)
        {
            case -1:
                dvMessage.Visible = true;
                lblMessage.Text = "Username and/or password is incorrect.";
                break;
            case -2:
                dvMessage.Visible = true;
                lblMessage.Text = "Account has not been activated.";
                break;
            default:
                if (!string.IsNullOrEmpty(Request.QueryString["ReturnUrl"]))
                {
                    FormsAuthentication.SetAuthCookie(username, chkRememberMe.Checked);
                    Response.Redirect(Request.QueryString["ReturnUrl"]);
                }
                else
                {
                    FormsAuthentication.RedirectFromLoginPage(username, chkRememberMe.Checked);
                }
                break;
        }
    }
}
 
VB.Net
Protected Sub ValidateUser(sender As Object, e As EventArgs)
    Dim username As String = txtUsername.Text.Trim()
    Dim password As String = txtPassword.Text.Trim()
    Dim userId As Integer = 0
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As New SqlConnection(constr)
        Using cmd As New SqlCommand("Validate_User")
            cmd.CommandType = CommandType.StoredProcedure
            cmd.Parameters.AddWithValue("@Username", username)
            cmd.Parameters.AddWithValue("@Password", password)
            cmd.Connection = con
            con.Open()
            userId = Convert.ToInt32(cmd.ExecuteScalar())
            con.Close()
        End Using
        Select Case userId
            Case -1
                dvMessage.Visible = True
                lblMessage.Text = "Username and/or password is incorrect."
                Exit Select
            Case -2
                dvMessage.Visible = True
                lblMessage.Text = "Account has not been activated."
                Exit Select
            Case Else
                If Not String.IsNullOrEmpty(Request.QueryString("ReturnUrl")) Then
                    FormsAuthentication.SetAuthCookie(username, chkRememberMe.Checked)
                    Response.Redirect(Request.QueryString("ReturnUrl"))
                Else
                    FormsAuthentication.RedirectFromLoginPage(username, chkRememberMe.Checked)
                End If
                Exit Select
        End Select
    End Using
End Sub
 
 
Redirect User to Home page if already logged in, in same browser
Inside the Page Load event of the Login page, first we verify whether the User is authenticated using the IsAuthenticated property. If the user is authenticated then he is redirected directly to the Home page which is set as DefaultUrl in the FormsAuthentication setting of the Web.Config file.
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (this.Page.User.Identity.IsAuthenticated)
    {
        Response.Redirect(FormsAuthentication.DefaultUrl);
    }
}
 
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Me.Page.User.Identity.IsAuthenticated Then
        Response.Redirect(FormsAuthentication.DefaultUrl)
    End If
End Sub
 
Responsive Login Form inside Bootstrap Modal Popup in ASP.Net
 
 
Home Page
After successful login user will be redirected to this page.
 
 
HTML Markup
In this page I have made use of ASP.Net LoginName control to display the name of the Logged In user and LoginStatus control to allow user Logout.
<script type="text/javascript" src='https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js'></script>
<script type="text/javascript" src='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/js/bootstrap.min.js'></script>
<link rel="stylesheet" href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/css/bootstrap.min.css'
    media="screen" />
<form id="form1" runat="server">
<div>
    <h2>
        Welcome</h2>
    <hr />
    <h4>
        <asp:LoginName ID="LoginName1" runat="server" Font-Bold="true" />
    </h4>
    <br />
    <asp:LoginStatus ID="LoginStatus1" runat="server" CssClass = "btn btn-warning" />
</div>
</form>
 
Responsive Login Form inside Bootstrap Modal Popup in ASP.Net
 
 
Namespaces
You will need to import the following namespaces.
C#
using System.Web.Security;
 
VB.Net
Imports System.Web.Security
 
 
Redirect User to Login page if not logged in
Inside the Page Load event of the Home page, first we verify whether the User is authenticated using the IsAuthenticated property. If the user is not authenticated then he is redirected back to the Login page using FormsAuthentication RedirectToLoginPage method.
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.Page.User.Identity.IsAuthenticated)
    {
        FormsAuthentication.RedirectToLoginPage();
    }
}
 
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not Me.Page.User.Identity.IsAuthenticated Then
        FormsAuthentication.RedirectToLoginPage()
    End If
End Sub
 
Responsive Login Form inside Bootstrap Modal Popup in ASP.Net
 
 
Web.Config Configuration
You will need to add the following configuration in the Web.Config file in the <system.web> section.
<authentication mode="Forms">
  <forms defaultUrl="~/Home.aspx" loginUrl="~/Login.aspx" slidingExpiration="true" timeout="2880"></forms>
</authentication>
 
 
Screenshot
Responsive Login Form inside Bootstrap Modal Popup in ASP.Net
 
 
Downloads