Thursday, April 14, 2011

Call WebMethod from Javascript in ASP.NET

I needed to be able to remove a session variable from javascript so this post will
talk about how to call a webmethod from javascript to remove a session item. I will
be utilizing a JS file, ASP.NET page with a WebMethod exposed in it and an
user control. The basis of this is a few things: First we need an

<pre><asp:scriptmanager></pre> on the ASPX page with the EnablePageMethods property set to true:

    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
            <uc1:ucMyControl ID="ucMyControl1" runat="server" />

Second we need to expose a static function in our ASPX code behind so it can be available to our javascript file.

    public static string ClearSessionItem(string item)
        if (HttpContext.Current.Session[item] != null)
             return "true";
             return "false";

Note the [WebMethod] above the function and that the function is static. This is what allows us to make it available to the javascript file.

Please make sure to add the statement using System.Web.Services; into the ASPX page, otherwise [WebMethod] will throw an error when compiling.

Third we need a ScriptProxyManager on the ASCX control with a reference to your JS file. This will also take care of including the JS file for your control as well so there is no need to add the <script src=....> tag. Put this as the first thing in your ASCX control.

<asp:ScriptManagerProxy ID="smp1" runat="server">
        <asp:ScriptReference Path="myJSFile.js" />

Fourth we need the code from the JS file to bring it all together:

   function ClearSessionItem(key) {
       //alert("I made it inside ClearSessionItem: " + key);     
       //now call server side method
       PageMethods.ClearSessionItem(key, OnSucceeded, OnFailed);

   function OnSucceeded(result, userContext, methodName) {
       if(result == "true")
            //do something
            //do something

   function OnFailed(error, userContext, methodName) {
       if (error !== null) {
          alert("An error occurred: " + error.get_message());


Anywhere in your javascript you can call the ClearSessionItem() method. Such as

function MyFunction(item){    

Also you could call it via an onclick event with an HTML element such as:

<pre><span onclick="ClearSessionItem('MySessionItem')">Clear Item</span></pre>

Of course you can use this concept for almost about anything. It allows you to not have a seperate
ASMX file (Web Service) in your project. Again, the concept here allows you to call
a server side method inside javascript.

No comments:

Post a Comment