Calling methods in an ASP.NET page using jQuery
This is a very neat way to call a specific method in an ASP.NET page without going through the whole page event cycle. And you can use the Ajax enabled javascript library of your choise. I will be using jQuery in this example.
First of all make sure you have this section in your web.config. Otherwise you'll be getting the whole content of the page and the method you are thinking you're calling won't be reached at all.
So, step number one, make sure this is in your web.config:
<system.web>
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</httpModules>
</system.web>
Step number two, open your default.aspx.cs-file and add our new method GetName. Notice the [WebMethod] attribute before the method. This is what exposes the method to outside calls. Also notice that the method is both static and public.
Parameters is passed from jQuery as post data. But notice that you don't need Request.Form at all and that it's translated to normal function parameters.
public partial class _Default : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
}
[WebMethod]
public static string GetName(string name) {
return "Your name is " +name ;
}
}
Okay, we're nearly there. Now we just need to call the method. On the default.aspx page, include the jQuery script in the head. I'll show another neat thing here. How you can use Google's CDN (Content Delivery Network) to fetch the jQuery library, thus speeding up the loading of your page. Instead of your local jQuery javascript file, point toward this:
http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js
Here's the complete code for your aspx page (don't delete your first row (<%@ Page ..) though!):
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Example</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
function getDataFromWebMethod() {
$.ajax({
type: "POST",
url: "Default.aspx/GetName",
data: "{ name: \"John Doe\" }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg.d);
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<a href="javascript:getDataFromWebMethod();">Get Data</a>
</div>
</form>
</body>
</html>
[Code updated 2011-03-22. The return value is accessed by msg.d and not just msg]
Related posts: