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

Calling Server Side Code from Client Side using Ajax

Rate me:
Please Sign up or sign in to vote.
4.32/5 (14 votes)
25 May 2009CPOL2 min read 57.8K   2   64  
Ajax PageMethods in JavaScript use to call server side methods in Client side
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--------------------------------------------------------------------------->  
<!--                           INTRODUCTION                                

 The Code Project article submission template (HTML version)

Using this template will help us post your article sooner. To use, just 
follow the 3 easy steps below:
 
     1. Fill in the article description details
     2. Add links to your images and downloads
     3. Include the main article text

That's all there is to it! All formatting will be done by our submission
scripts and style sheets. 

-->  
<!--------------------------------------------------------------------------->  
<!--                        IGNORE THIS SECTION                            -->
<html>
<head>
<title>The Code Project</title>
<Style>
BODY, P, TD { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10pt }
H2,H3,H4,H5 { color: #ff9900; font-weight: bold; }
H2 { font-size: 13pt; }
H3 { font-size: 12pt; }
H4 { font-size: 10pt; color: black; }
PRE { BACKGROUND-COLOR: #FBEDBB; FONT-FAMILY: "Courier New", Courier, mono; WHITE-SPACE: pre; }
CODE { COLOR: #990000; FONT-FAMILY: "Courier New", Courier, mono; }
</style>
<link rel="stylesheet" type="text/css" href="http://www.codeproject.com/App_Themes/NetCommunity/CodeProject.css">
</head>
<body bgcolor="#FFFFFF" color=#000000>
<!--------------------------------------------------------------------------->  


<!-------------------------------     STEP 1      --------------------------->
<!--  Fill in the details (CodeProject will reformat this section for you) -->

<pre>
Title:       Calling Server side code from Client side using PageMethods In AJAX
Author:      M.Muthupandiammal
Email:       muthu.pandiammal@gmail.com
Member ID:   12345
Language:     C# 2.0 
Platform:     .NET 2.0,3.0 etc
Technology:  ASP.NET, GDI+
Level:        Intermediate
Description: Calling Server side code function from Client side Javascript without postbacks
</pre>


<!-------------------------------     STEP 3      --------------------------->

<!--  Add the article text. Please use simple formatting (<h2>, <p> etc)   --> 

<h2>Introduction</h2>

<p>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


<h2>Step 1</h2>

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


<h2>Step 2</h2>

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

<h2>Step 3</h2>
<p>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


<p>Blocks of code should be wrapped in &lt;pre> tags like this:

<pre>
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(); 
} 
}
</pre>



<h2>Step 4</h2>

<p>We will now transform this method as a PageMethod and then call this method GetContactName() from client side code; i.e. using JavaScript. To enable the method as a PageMethod, add the attribute [WebMethod] on top of the method:
<pre>
[System.Web.Services.WebMethod] 
public static string GetContactName(string custid) 
{ 
}
</pre>

<p>At the sametime, add the attribute EnablePageMethods="true" to the ScriptManager

<h2>Step 5</h2>
<p>Let us now create the JavaScript that will call this server side code. Add a javascript file called script.js 
<pre>
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()); 
} 


</pre>


<h2>Step 6</h2>
<p>We now need to reference this JavaScript file from our aspx page and invoke the �CallMe()� method whenever the textbox loses focus. To do so: 
Add a reference to the javascript file in the body tag as shown below: 
<body> 
<script type="text/javascript" language="javascript" src="script.js"> </script> 
<form id="form1" runat="server"> 
<h2>Step 7</h2>
<p>To invoke the methods whenever the textbox looses focus, add these lines of code in the Page_Load() event
<pre>
if (!Page.IsPostBack) 
{ 
txtId1.Attributes.Add("onblur", "javascript:CallMe('" + txtId1.ClientID + "', '" + txtContact1.ClientID + "')"); 
txtId2.Attributes.Add("onblur", "javascript:CallMe('" + txtId2.ClientID + "', '" + txtContact2.ClientID + "')"); 
}
</pre>
<p>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



<p> Good Luck .........Thanks....
</body>

</html>

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

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


Written By
Acusis Software pvt ltd
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions