Translate

Wednesday 23 July 2014

Calling a static "page method" from Javascript using MS AJAX

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("Gksamy"));
    }
</script>