Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Visual Studio 2010 and Microsoft SQL 2008- Authentication System using ASP.NET (JQuery, Json and Web services)

0.00/5 (No votes)
9 May 2010 1  
How to call server side methods or functions directly using JQuery in ASP.NET C#

Introduction

In this article, we will be looking at the login page of the application. This is the first page that any user wanting to use our application is going to be faced with and the most important one in this section. The login script plays a very important role in this application.

Background

An authentication system allows certain online material to be accessible only to a select few. This tutorial illustrates the basic construction of an authentication system using ASP.NET.

In this tutorial, I'll be using JQuery to make AJAX calls to the server. I'll also explain how to call server side methods or functions directly using JQuery in ASP.NET C#.

Overview

  1. Create Project in Visual Studio
  2. Solution Explorer
  3. Database
    1. Create Table
    2. Insert statement
    3. Create Store Procedure
  4. Web.Config
  5. Server Side
  6. Client Side

Create Project in Visual Studio

Open your Visual Studio 2010 and create a New Project as shown below:

Solution Explorer

By default, Jquery is added in your project, when you create a new Web site in Visual Studio 2010, as shown in the below diagram:

Database

I will consider that you know how to create a database, else I have created a database with name testing.

UserLogin Table

Create a Table with name userLogin.

CREATE TABLE [dbo].[UserLogin](
	[loginid] [bigint] IDENTITY(1,1) NOT NULL,
	[username] [varchar](30) NOT NULL,
	[password] [varchar](50) NOT NULL,
	[email] [varchar](255) NOT NULL,
	[user_type] [varchar](45) NOT NULL,
	[disabled] [bit] NOT NULL,
	[activated] [bit] NOT NULL,
 CONSTRAINT [PK_UserLogin] PRIMARY KEY CLUSTERED 
(
	[username] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, 
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON,
 ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

As you have seen, username is the primary key to prevent a duplicate username, and loginid is the identity (auto Increment).

Insert Records

Insert Records into UserLogin Table.

 INSERT INTO USERLOGIN VALUES ('aamir','hasan','hasan@studentacad.com','user',0,0)
 INSERT INTO USERLOGIN VALUES ('admin','admin','aamirhasan@studentacad.com','admin',0,0)

Store Procedure

I have created a stored procedure with name spx_checkuserlogin. The stored procedure will return 0 if user does not exist in the Userlogin table, or else it will return user id.

CREATE PROCEDURE [dbo].[SPX_CHECKUSERLOGIN]

      @USERNAME VARCHAR(50),
      @PASSWORD VARCHAR(50)

AS

BEGIN
declare @value bigint
    SET NOCOUNT ON;

SELECT @value=	 LOGINID FROM USERLOGIN 
	WHERE USERNAME = @USERNAME AND PASSWORD = @PASSWORD 
	AND [DISABLED]=0 
 select ISNULL(@value,0)
END

Server Side

I have created WebMethod which will accepts username and password and sends to stored procedure.

[System.Web.Services.WebMethod]
        public static string CheckUserName(string userName,string passWord)
        {
         string returnValue = string.Empty;
            try
            {
                string consString = ConfigurationManager.ConnectionStrings
				["testingConnectionString"].ConnectionString;
                SqlConnection conn = new SqlConnection(consString);
                SqlCommand cmd = new SqlCommand("SPX_CHECKUSERLOGIN", conn);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@UserName", userName.Trim());
                cmd.Parameters.AddWithValue("@password", passWord.Trim());
                conn.Open();
                returnValue = cmd.ExecuteScalar().ToString();
                conn.Close();
            }
            catch(Exception ee)
            {
                returnValue = "error message: " + ee.Message;
            }
            return returnValue;
        }

Note: Method should be static.

Client Side

In aspx Page, HTML will collect username, password fields and input button with name Login.

  <div>
Username : <asp:TextBox ID="txtUserName" runat="server" 
	onkeyup = "OnKeyUp(this)" /><br />
Password:  <asp:TextBox ID="txtPassWord" 
	TextMode=Password runat="server" onkeyup ="OnKeyUp(this)"/><br />  
 <input id="btnCheck" type="button" value="Login" onclick = "CheckUserLogin()" />
 <br />
 <span id = "message"> </spa
</div> 

JQuery

Jquery is used to call server side method which will send username and password and get back response from the server side code.

function CheckUserLogin() {
        $.ajax({
            type: "POST",
            url: "default.aspx/CheckLogin",
            data: '{userName: "' + $("#<%=txtUserName.ClientID%>")[0].value + 
		'",passWord: "' + $("#<%=txtPassWord.ClientID%>")[0].value + '" }',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            failure: function (response) {
                alert(response);
            }
        });

The “'{userName: "' + $("#<%=txtUserName.ClientID%>")[0].value + '",passWord: "' + $("#<%=txtPassWord.ClientID%>")[0].value + '" }',” data parameter represents a username and password JSON object.

The above jQuery has the following properties and values given below:

$.ajax({

type:Reuest Type
url:Page URL/Method name.
data:Values.
dataTyle:"json".
success:Success Method.

}); 

Now add Reference of JQuery in your Head second at top of Page.

<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>  
<script type = "text/javascript"> 
function OnKeyUp(txt) {
            $("#message")[0].innerHTML = "";
        }
       
        function CheckUserLogin() {
        $.ajax({
            type: "POST",
            url: "default.aspx/CheckLogin",
            data: '{userName: "' + $("#<%=txtUserName.ClientID%>")[0].value + 
		'",passWord: "' + $("#<%=txtPassWord.ClientID%>")[0].value + '" }',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            failure: function (response) {
                alert(response);
            }
        });
    }
    function OnSuccess(response) {
        var mesg = $("#message")[0];

        if (response.d == 0) {
            mesg.style.color = "red";
            mesg.innerHTML = "Invalid Username and Password;";
        } else if (response.d > 0) {
            mesg.style.color = "green";
            mesg.innerHTML = "User ID:" + response.d.toString();
        } else {
            mesg.style.color = "red";
            mesg.innerHTML = "Error:" + response.d.toString();
        }    
    }
</script> 

As you’ll notice above, I am simply calling the CheckLogin Server side function in Default.aspx page and passing the TextBox values as parameter. Secondly, I have defined the success method OnSuccess that will be called to handle the response returned by the server.

History

  • 9th May, 2010: Initial post

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here