Login Panel JQuery in Asp.net – Login With Twitter Drop Down Style

I have searched a lot to find a complete work around on implementing Twitter style JQuery Login Panel with ajax in Asp.net C# & VB.net. Unfortunately i did not get any complete solution around the web. Hence decided to write an article on Login Panel JQuery in Asp.net C# & VB.net which will help my readers to quickly grab the code & the implementation as well. Finally to complete this example here i have used very simple CSS code to style the UI like Twitter and JQuery Ajax to call the aspx page web method. It’s very easy & simple to follow. So let’s start.

Login Panel JQuery in Asp.net AJAX

First of all we need to open our Visual Studio .NET and make a new ASP.NET web site like below:

  • Go to Visual Studio 2013
  • File -> New Web Site
  • Click OK

asp.net login page

Now open the Default.aspx code page to add the HTML controls div for your login panel. Find the end of the content section & paste below code just immediate before the end of content section.

    

<div id="login-panel">
			<label>Username: <input type="text" id="txtUsername" value="" /> </label>
			<label>Password: <input type="password" id="txtPassword" value="" /> </label>
			<input type="submit" id="cmdAuthenticate" value="Sign In" /> <small>Press ESC to close</small>
	</div>


Style your Login Panel JQuery in Asp.net:

Now time to style our Login Panel JQuery in Asp.NET. As mentioned earlier what we want to do? We want to achieve the Twitter like drop down login panel. To do that we need add some CSS. The below code will help you to do so. Go the solution explorer. Open the Site.css file under content & paste the below code just immediate before media queries.

#login-panel{
  position: absolute;
  top: 50px;
  right: 0px;
  width: 290px;
  padding: 10px 15px 5px 15px;
  background: #2a2a2a;
  font-size: 8pt;
  font-weight: bold;
  color: #FFF;

  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  border-radius: 5px;
 
  -webkit-box-shadow: 0px 1px 1px 0px rgba(255,255,255, .2), inset 0px 1px 1px 0px rgb(0,0,0);
  -moz-box-shadow: 0px 1px 1px 0px rgba(255,255,255, .2), inset 0px 1px 1px 0px rgb(0,0,0);
  box-shadow: 0px 1px 1px 0px rgba(255,255,255, .2), inset 0px 1px 1px 0px rgb(0,0,0);

  display: none; 
}
label{
  line-height: 1.8;
  display:block;
}

input[type="text"],
input[type="password"]{
  padding:10px;
  display:block;
  width:270px;
  margin-bottom:10px;
}

input[type="submit"]{
    float:right;
  background: #00ffff;
  border:1px solid #000;
  padding:10px 20px;
  display:block;
  margin-bottom:10px;

  -webkit-border-radius: 26px;
  -moz-border-radius: 26px;
  border-radius: 26px;
 
  -webkit-transition: all .15s ease-in-out;
  -moz-transition: all .15s ease-in-out;
  -o-transition: all .15s ease-in-out;
  transition: all .15s ease-in-out;
}

Here the main CSS property is position which is set to absolute means the div with id “login-panel” now absolutely positioned. And also the display property is set to “none” because we don’t want to see the login block before clicking on the login link. Rest of the code is self explanatory. Hope you can understand easily.

Time to Add JQuery Events:

Now we need to add some JQuery events like login link click to drop down the login block and “ESC” key event to hide it again. To do that add below JQuery code in your default.aspx page.

    
        // jQuery to show login panel
        $(document).ready(function () {
            $("#loginlink").click(function () {
                $("#login-panel").slideToggle(200);
            });

            $(function () {
                $("[id*=cmdAuthenticate]").bind("click", function () {
                    var user = {};
                    user.Username = $("[id*=txtUsername]").val();
                    user.Password = $("[id*=txtPassword]").val();
                    $.ajax({
                        type: "POST",
                        url: "Account/Login.aspx/ValidateUser",
                        data: '{user: ' + JSON.stringify(user) + '}',
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (Response_msg) {
                            alert(Response_msg.d);
                            $("#login-panel").hide(0);
                        }
                    });
                    return false;
                });
            });
        });

        //jQuery to hide login panel
        $(document).keydown(function (e) {
            if (e.keyCode == 27) {
                $("#login-panel").hide(0);
            }
        });

The code blocks are self explanatory except the ajax call, hence hoping no explanation required at all. I will back on ajax login later on.

Do a tiny modification in site.master page like below:

<li><a id="loginlink" href="#login">Log in</a></li>

Prepare Back End Database:

To complete the example now we need to do concentrate on authentication part. Before starting code we have to prepare our back end database table first. So first create the table like below:

CREATE TABLE [dbo].[Users](
	[UserID] [int] NOT NULL,
	[UserName] [nvarchar](max) NOT NULL,
	[Password] [char](10) NOT NULL,
	[IsActive] [bit] 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] TEXTIMAGE_ON [PRIMARY]

For security purpose we have to validate users through database SP. Hence create the SQL SErver Stored Procedure like below:

CREATE PROCEDURE [dbo].[Validate_User]
      @Username VARCHAR(MAX),
      @Password CHAR(10)
AS
BEGIN
      SET NOCOUNT ON;
      DECLARE @UserId INT
     
      SELECT @UserId = UserId FROM Users 
	  WHERE Username = @Username AND [Password] = @Password AND IsActive=1
     
      IF @UserId IS NOT NULL
      BEGIN
		SELECT @UserId [UserId] -- User found
      END
      ELSE
      BEGIN
            SELECT -1 -- User not found.
      END
END

Add some users in the database table so that we can check user validation after completion of the example Login Panel JQuery in Asp.NET.

Validate User Login using JQuery Ajax:

At this stage almost all are set including JQuery login panel. Finally We need to add a web method in aspx page so that we can execute the previously build SQL Server Stored Procedure to validate a user based on the input provided by login panel. And our target is to validate user through JQuery AJAX.

We are almost done. Just find the default login validation page under Account hierarchy. The page name is Login.aspx. Open it up and paste the below web method just immediate after the page load event:

        [System.Web.Services.WebMethod]
        public static string ValidateUser(Users user)
        {
            int userId = -1;
            string constr = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("Validate_User"))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@Username", user.Username);
                    cmd.Parameters.AddWithValue("@Password", user.Password);
                    cmd.Connection = con;
                    con.Open();
                    userId = Convert.ToInt32(cmd.ExecuteScalar());
                    con.Close();
                }
            }
            string IsValidate = string.Empty;
            switch (userId)
            {
                case -1:
                    IsValidate = "Username or password is incorrect.";
                    break;
                default:
                    IsValidate = "Welcome...";
                    break;
            }

            return IsValidate;
        }

        public class Users
        {
            public string Username { get; set; }
            public string Password { get; set; }
        }

Make sure that you have added the below settings to establish the SQL Server connection in web.config file:

  <connectionStrings>
    <!--<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-WebSite1-19a752f6-cad5-4757-a9aa-597a9d944f4b;AttachDbFilename=|DataDirectory|\aspnet-WebSite1-19a752f6-cad5-4757-a9aa-597a9d944f4b.mdf;Integrated Security=SSPI" providerName="System.Data.SqlClient" />-->
    <add name="DBConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=TESTDB;Trusted_Connection=yes;" providerName="System.Data.SqlClient"/>
  </connectionStrings>

And also add the below namespaces on top of the Login.aspx.cs page:

using System.Web.Security;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;

Now time to Conclude:

Finally our coding part successfully completed. It’s a time to test the Login Panel JQuery in Asp.net – Login With Twitter Drop Down Style. Just run your project hope you are getting the drop down style login page & also can authenticate yourself from database. Furthermore to give you the comfort I am sharing my output below:


Fig: Demo on How to Create Login Panel JQuery in Asp.net – Login With Twitter Drop Down Style

Some common Exceptions:

During development time you may face some unwanted exceptions. Though you are good enough(since you are trying to implement Twitter like Login in Asp.NET C# & VB.NET) to overcome those but i think i have to share the below unexpected exception so that you can run the example in one go.

Exception Name: Authentication failed
Source: JQuery AJAX Success Call Back Method
Solution: Just comment out the following line or change it’s RedirectMode from App_Code\RouteConfig.cs:

//settings.AutoRedirectMode = RedirectMode.Permanent;

Download Login Panel JQuery in Asp.net C# & VB.NET source code:

Download Code Example C#        Download Code Example VB.Net

Hope i can help you to implement the twitter style Login Panel Jquery in Asp.NET. If you like this post please share us to grow in your social networks using below links. Also finally if you face any issue with my code or if you have any best approach please don’t hesitate to share through comment.

HAPPY CODING !!

Posted in .Net, Ajax, Asp.net, C#, Client, JQuery, VB.Net

Leave a Reply

Your email address will not be published. Required fields are marked *

AlphaOmega Captcha Classica  –  Enter Security Code
     
 

*