How to call a C# Web(Page) Method from Javascript using ScriptManager

Atlas (Javascript Library) gave us the ability to easily call Web method from JavaScript. Microsoft AJAX has gone one step further! We can now call web methods in the code behind of the current page from Javascript. Here’s how:
For Enable Page Methods on your ScriptManager set the EnablePageMethods=”true” attribute

<asp:ScriptManager&nbsp;ID="ScriptManager1"&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;EnablePageMethods="true"&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;EnablePartialRendering="true"&nbsp;runat="server"&nbsp;/>

For this you must mark your method as static and give it the Web-method 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;
}

For Call it from Javascript you need 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>
Tagged , . Bookmark the permalink.

Leave a Reply