Using jQuery to directly call ASP.NET AJAX page methods


Here I am looking to explain how to call page methods using jQuery.

Step 1: Define your Page Methods in code behind:

[WebMethod]
    public static int MyMethod1()
    {
        return 13;
    }
    [WebMethod()]
    public static string MyMethod2(string a, int b)
    {
        return a + " –> " + b.ToString();
    } 

Step 2: Include the jQuery Library on Default.aspx page:

<script src="Js/jquery.min.js" type="text/javascript"></script> 

If you do not have jQuery file in Js folder then use following:

<script type="text/javascript"  src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"> 

Step 3: Now Write the code to Call Page method:

<script type="text/javascript">
        function PageMethod(fn, paramArray, successFn, errorFn) 
        { 
            var pagePath = window.location.pathname; 
            //Create list of parameters in the form : {"paramName1":"paramValue1","paramName2":"paramValue2"} 
            var paramList = ”; 
            if (paramArray.length > 0) 
            { 
                for (var i=0; i<paramArray.length; i+=2) 
                { 
                    if (paramList.length > 0)
                        paramList += ‘,’; 
                    paramList += ‘"’ + paramArray[i] + ‘":"’ + paramArray[i+1] + ‘"’; 
                } 
            } 
            paramList = ‘{‘ + paramList + ‘}’; 
            //Call the page method 
            $.ajax({ 
                type: "POST", 
                url: pagePath + "/" + fn, 
                contentType: "application/json; charset=utf-8", 
                data: paramList, 
                dataType: "json", 
                success: successFn, 
                error: errorFn 
            }); 
        } 
        function AjaxSucceeded (result)
        {
            alert(result.d);
            $("#Result").text("Result : " + result.d);
        }
        function AjaxFailed (result)
        {
            alert("Error on Page");
        }
        function CallPageMethod1()
        {          
            PageMethod("MyMethod1", [], AjaxSucceeded, AjaxFailed);                       
            return false;
        }
         function CallPageMethod2()
        {     
            PageMethod("MyMethod2",["a", "value", "b", 2], AjaxSucceeded, AjaxFailed);           
            return false;
        }
    </script> 

Step 4: To Test your code use following html on default.aspx:

<form id="form1" runat="server">
        <h1>
            Using jQuery To Call ASP.NET Page Methods and Web Services</h1>
        <div> 
<asp:Button ID="Button1" runat="server" Text="With No Parameter" OnClientClick="return CallPageMethod1();" />
   <asp:Button ID="Button2" runat="server" Text="With Parameter" OnClientClick="return CallPageMethod2();" />
        </div>
        <div id="Result">
        </div>
    </form> 

jQuery makes an AJAX call to the MyMethod1 & MyMethod2 page method and replaces the div’s text with its result.

Very Simple!!!

Hope You will also get benefit from this.

Jai Ganesh

Related Post:

https://ramanisandeep.wordpress.com/2009/09/22/calling-web-service-methods-using-asp-net-ajax/

Advertisements

10 thoughts on “Using jQuery to directly call ASP.NET AJAX page methods

    1. hi nawaz,
      i have tested code for you it works fine..

      give me yr id i send you the code …

      that will help you.

    1. hi kanglin ,
      just try to do the following to allow code to work in master page as well.

      1. Include the jQuery Library on Content Page rather than putting it in head tag of master page. (Step 2)
      2. Put the javascript code in content page as well ( step 3)

      This is will help..

  1. Hi,
    i have little changed in code above and run it on IE , Firefox and safari.
    it does work in IE, but not in Firefox and safari, why?
    java script is enable on
    both browser.is there some thing more to set on browser setting.

  2. hi,
    How to call websevise script Method from External JS (javascrip) file
    i m getting (web service name + )object undefine Error
    please replay me

  3. Hello Ramani,
    The code is working fine in visual studio 2010. but it doesn’t work in visual studio 2005. Please any suggestions ?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s