Thursday, 7 May 2009

Calling server side ASP.NET method from jQuery

I was recently looking at calling a server side method from an ASP.NET 3.5 application using jQuery. The following example has a server side method that returns some HTML markup from a database to jQuery, which then inserts it into the page markup.

Server side code, in Default.aspx:


using System.Web.Services;

[WebMethod(true)]
>(public static string getMarkup()
{
return "<h3>Test Markup</h3>";
}


You need to make the method static and include the WebMethod(true) operator above it. You can also use the following code to call a WebMethod from an asmx or WCF web service.

You call this from the client side jQuery code using:


$("#loadHome").click(function(){
$.ajax({
type: "POST",
url: "./Default.aspx/getMarkup",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result){
$("#contentDiv").html(result.d);
}
});
});


This uses the jQuery ajax method to get the data from the server side method, which is returned as a JSON object. You use the .d notation on the JSON object to get the result supplied from the server side.

If you want to send any data to the method, send as a JSON object. For example if you had a server side method that takes 2 params, orderId and customerId, you would use:

var data = "{orderId:'2',customerId:'99'}";

No comments:

Free Hit Counter