Click here to Skip to main content
Click here to Skip to main content

Calling Server Side Code from Client Side using Ajax

, 25 May 2009
Rate this:
Please Sign up or sign in to vote.
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.

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

  • 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)

Share

About the Author

Muthupandiammal
Acusis Software pvt ltd
India India
No Biography provided

Comments and Discussions

 
GeneralNice PinmemberSteve Wellens25-May-09 5:06 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140821.2 | Last Updated 25 May 2009
Article Copyright 2009 by Muthupandiammal
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid