Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Calling Server Side Code from Client Side using Ajax

4.32/5 (14 votes)
25 May 2009CPOL2 min read 58.6K   2  
Ajax PageMethods in JavaScript use to call server side methods in Client side

Introduction

Using Microsoft ASP.NET AJAX is to call ASP.NET Web services (*.asmx files) from the browser by using client script. The script can call a webservice containing server-based methods (Web methods) and invoke these methods without a postback and without refreshing the whole page. The option we are going to use in this article involves PageMethods. A PageMethod is basically a public static method that is exposed in the code-behind of an aspx page and is callable from the client script. PageMethods are annotated with the [WebMethod] attribute. The page methods are rendered as inline JavaScript

Step 1

Create an ASP.NET AJAX enabled website. Go to File > New > Website > ASP.NET AJAX-Enabled Web Site. Give the solution a name and location and click Ok.

Step 2

Drag and drop label and textbox controls. We will be accepting the CustomerID from the user in the textbox and displaying the ‘ContactName’ in the label Add the connection string in Config section tag in web.config file.

Step 3

Currently we will add a method, ‘GetContactName()’ which will accept a CustomerID and return the Contact Name information from the Northwind database, Customer table. We will then transform this method as a PageMethod.

C#
public static string GetContactName(string custid) 
{ 
if (custid == null || custid.Length == 0) 
return String.Empty; 
SqlConnection conn = null; 
try 
{ 
string connection = ConfigurationManager.ConnectionStrings
			["NorthwindConnectionString"].ConnectionString; 
conn = new SqlConnection(connection); 
string sql = "Select ContactName from Customers where CustomerId = @CustID"; 
SqlCommand cmd = new SqlCommand(sql, conn); 
cmd.Parameters.AddWithValue("CustID", custid); 
conn.Open(); 
string contNm = Convert.ToString(cmd.ExecuteScalar()); 
return contNm; 
} 
catch (SqlException ex) 
{ 
return "error"; 
} 
finally 
{ 
conn.Close(); 
} 
}

Step 4

We will now transform this method as a PageMethod and then call this method GetContactName() from the client side code; i.e. using JavaScript. To enable the method as a PageMethod, add the attribute [WebMethod] on top of the method:

C#
[System.Web.Services.WebMethod] 
public static string GetContactName(string custid) 
{ 
}

At the same time, add the attribute EnablePageMethods="true" to the ScriptManager.

Step 5

Let us now create the JavaScript that will call this server side code. Add a JavaScript file called script.js.

JavaScript
function CallMe(src,dest) 
{ 
var ctrl = document.getElementById(src); 
// call server side method 
PageMethods.GetContactName(ctrl.value, CallSuccess, CallFailed, dest); 
} 
// set the destination textbox value with the ContactName 
function CallSuccess(res, destCtrl) 
{ 
var dest = document.getElementById(destCtrl); 
dest.value = res; 
} 
// alert message on some failure 
function CallFailed(res, destCtrl) 
{ 
alert(res.get_message()); 
} 

Step 6

We now need to reference this JavaScript file from our aspx page and invoke the ‘CallMe()’ method whenever the textbox looses focus. To do so: Add a reference to the JavaScript file in the body tag as shown below:

JavaScript
<body> <script type="text/javascript" language="javascript" src="script.js"> 
	</script> <form id="form1" runat="server"> 

Step 7

To invoke the methods whenever the textbox looses focus, add these lines of code in the Page_Load() event:

JavaScript
if (!Page.IsPostBack) 
{ 
txtId1.Attributes.Add("onblur", 
    "javascript:CallMe('" + txtId1.ClientID + "', '" + txtContact1.ClientID + "')"); 
txtId2.Attributes.Add("onblur", 
    "javascript:CallMe('" + txtId2.ClientID + "', '" + txtContact2.ClientID + "')"); 
}

As shown above, we are using the Attributes.Add that lets us add an attribute to the server control’s System.Web.UI.AttributeCollection object. The function ‘CallMe’ kept in the ‘script.js’ file will be invoked. We are passing the source and destination textboxes as parameters. The source textbox will contain the CustomerID. The CustomerID will be looked up in the Customers table and the corresponding ‘ContactName’ will be retrieved in the destination textbox.

Good luck... thanks!

History

  • 25th May, 2009: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)