Click here to Skip to main content
Email Password   helpLost your password?

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.

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:

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

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:

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

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

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralGood Article
Rehan Hussain
2:40 17 Feb '10  
simple and stright
Generalplz help me understand the server method function parameters
Emad Suria
21:44 24 Jul '09  
// call server side method
PageMethods.GetContactName(ctrl.value, CallSuccess, CallFailed, dest);

could you plz elaborate on how come ur passing 4 params in function declared to accept 1 param; and 2 of them are functions. How does it work?

Emad Suria

GeneralRe: plz help me understand the server method function parameters
ali_reza_zareian
22:56 25 Aug '09  
be aware, its javascript function.read more about javascript language.
GeneralAnother related article that will help you
rajendra malav
1:58 6 Jul '09  
http://rajendramalav.blogspot.com/[^]

raj

GeneralA little help
dhaval42
5:21 24 Jun '09  
Hi,

First of all i must appreciate this post. Really nice but i am getting an error and the code mentioned is not working. I am getting a javascript error as "'PageMethods' is undefined". I am using VS 2008 so i dont think AJAX enabled web site should be an issue here. Also i have a script manager in place and still the error is persistant. Please help. Thanks in advance.

modified on Thursday, June 25, 2009 8:59 AM

GeneralUseful contribution
Sanjay4India
3:37 29 May '09  
Thats a useful contribution.Keep posting such articles. Thumbs Up

S#

GeneralNice
Steve Wellens
6:06 25 May '09  
Simple and clear.

Steve Wellens


Last Updated 25 May 2009 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010