Calling a static "page method" from Javascript using MS AJAX
Atlas gave us the ability to easily call Web Services from JavaScript. MS AJAX has gone one step further! We can now call methods in the codebehine of the current page from Javascript. Here's how:
This is designed for v1.0.61025.0 of AJAXExtensionsToolbox.dll
Enable Page Methods on your ScriptManager
Set the EnablePageMethods attribute to true
<asp:ScriptManager ID="ScriptManager1"
EnablePageMethods="true"
EnablePartialRendering="true" runat="server" />
Mark your method as static and give it the WebMethod attribute
The method has to be declared static. It must also be marked with the WebMethod attribute. You'll probably find that you need to include System.Web.Services
using System.Web.Services;
[WebMethod]
public static string MyMethod(string name)
{
return "Hello " + name;
}
Call it from Javascript
To call the method from javascript you need to append PageMethods. to the front of the method name.
<script>
function test(){
alert(PageMethods.MyMethod("Paul Hayman"));
}
</script>
| Author |
: Paul Hayman |
| Published |
: Wednesday, 11 July, 2007 |
Paul is the COO of kwiboo ltd consultant and has more than a decade of IT consultancy experience. He has consulted for a number of blue chip companies and has been exposed to the folowing sectors: Utilities, Telecommunications, Insurance, Media, Investment Banking, Leisure, Legal, CRM, Pharmaceuticals, Interactive Gaming, Mobile Communications, Online Services.
Paul is the COO and co-founder of kwiboo (http://www.kwiboo.com/) and is also the creator of GeekZilla.