Click here to Skip to main content
15,891,033 members
Articles / Web Development / ASP.NET

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

Rate me:
Please Sign up or sign in to vote.
4.00/5 (8 votes)
9 May 2010CPOL2 min read 56K   1.3K   28   5
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.

SQL
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.

SQL
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.

SQL
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.

C#
[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.

ASP.NET
  <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.

JavaScript
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:

JavaScript
$.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.

JavaScript
<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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Dotnetplace
Pakistan Pakistan
Aamir Hasan is a Sr. Software Engineer and Technical Lead in a US based firm, having five years of experiences working in Software Design, Software Analysis, Business Intelligence, Web Development, Consultancy and Training, using SQL Server, .NET Framework and provides consultancy on how to design and develop .NET application with database solutions. Aamir is the founder of www.aspxtutorial.com and dotnetplace.com. He is a Microsoft Certified and SEO professional too. He is capable of coordinating off-shore high level web development projects.


asp.net Tutorial, sample code and demo

Comments and Discussions

 
Questionnice article! Pin
hjlaoye8-Mar-20 0:31
hjlaoye8-Mar-20 0:31 
GeneralMy vote of 3 Pin
Member 98779105-Sep-13 5:33
Member 98779105-Sep-13 5:33 
GeneralMy vote of 1 Pin
Chuck Borcher30-Mar-11 8:05
Chuck Borcher30-Mar-11 8:05 
GeneralGood Effort.. Pin
Mohamad Kaifi10-May-10 23:49
Mohamad Kaifi10-May-10 23:49 
Generalcool! Pin
Nitin S10-May-10 22:02
professionalNitin S10-May-10 22:02 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.