Apr
30th

Call ASP.Net WebMethod from jQuery

Filed under ASP.Net, Web Development | Posted by Shahar A

I’ve read about jQuery in this great post Five recommendations for starting a startup with ASP.NET and wanted to play with it and see
how easy it is to call a WebMethod from
sQuery. I Started by reading some of the great Tutorials and downloaded the code from here.
I Created a test web project, copied the jQuery file to it and added a WebMethod that waits a random time and return true/false randomly:

public partial class _Default
               : System.Web.UI.Page
{
    …
    public class MethodReturnedValue
    {
        public int Time { get; set; }
        public bool Success { get; set; }
    }           

    [WebMethod(true)]
    public static MethodReturnedValue SomeMethod()
    {
        MethodReturnedValue retVal = new MethodReturnedValue();
        retVal.Time = random.Next(5000);
        Thread.Sleep(retVal.Time);
        if (random.Next() % 2 == 0)
        {
            retVal.Success = true; ;
        }
        else
        {
            retVal.Success = false;
        }
        return retVal;
    }
}

Than, I added few html elements:

<body>
    <form id=“form1″ runat=“server”>
    <asp:ScriptManager ID=“SM1″ EnablePageMethods=“true” runat=“server” />
    <div>
            <a id=“execute_page_method” href=“http://jquery.com/”>Click!</a>
            <img id=“ajax_loading_image” src=“ajax-loader.gif” alt=“Ajax Loader” />
            <label id=“message” >hello</label>
    </div>
    </form>
</body>

and style

<style type=“text/css”>
    a { float:left; width:30px;}
    img {float:left; width:30px; margin-left:10px; }
    label { float:left; margin-left:10px; }
</style>

I want to activate the web method when clicking the anchor, than display a ajax loading image which I downloaded from here, and when the call returns change the color of the body and display a message according to the values in the result. This is the javascript code:

<script src=“jquery-1.2.3.js” type=“text/javascript”></script>
<script type=“text/javascript”>           

    $(document).ready(function(){           

        // Initialization                            
        $(“#ajax_loading_image”).hide();           

        // mousemove event
        $().mousemove(function(e){
            window.status = e.pageX +‘, ‘+ e.pageY;
        });            

        // hook up the click event            
        $(“#execute_page_method”).click(function(){           

            $(“#message”).text(“I’m working…”) ;
            $(“#ajax_loading_image”).show(“fast”);
            $(“#execute_page_method”).hide(“fast”);           

            // Call some page method…
            PageMethods.SomeMethod(function(result, userContext, methodName){           

                $(“#ajax_loading_image”).hide(“slow”);
                $(“#execute_page_method”).show(“slow”);           

                if( result.Success == true )
                {
                    $(“body”).css(“background”,“Green”);
                }
                else
                {
                    $(“body”).css(“background”,“Red”);
                }           

                $(“#message”).text( “This took me “ + result.Time + ” milliseconds…  “ );           

            });
            return false ;
        });           

    });           

</script>

As you can see, I hook up the click event of execute_page_method element, call the page method and handle the callback with anonymous function.

I Like jQuery since it makes the code very readable, and although i used only the very basic of it, It has many great features that will save you lots of work…

Liked this post? Please, press my buttons! These icons link to social bookmarking sites where readers can share and discover new web pages.
  • description
  • description
  • bodytext
  • Live
  • YahooMyWeb
  • Google
  • Sphinn
  • del.icio.us
  • Facebook
  • Slashdot
  • StumbleUpon
  • Technorati
  • BlinkList
  • Netvouz
  • Propeller
  • TwitThis
  • Reddit
Tags: , , , , ,


7 Responses to “Call ASP.Net WebMethod from jQuery”

  1. By Kevin Deenanauth on Apr 30, 2008 | Reply

    Great work!

  2. By superjason on Apr 30, 2008 | Reply

    I don’t get it. What does jQuery have to do with calling the server method?

    It looks like the line calling the server method is standard JavaScript, and you just did some fancy effects with jQuery.

  3. By Joel on Apr 30, 2008 | Reply

    The title is a little misleading, you’re not actually calling the web method with jQuery. In fact you’re doing everything with jQuery EXCEPT call the web method - still a nice example for people new to jQuery.

  4. By Shahar A on Apr 30, 2008 | Reply

    The call is in JavaScript, the purpose was to show a begginer example on how to hook the event and handle the result with the help of jQuery.

  5. By Darrell on May 1, 2008 | Reply

    I like jQuery but also like the asp.net ajax framework. Personally I would use one or the other on a website not both.

  6. By Daniel on May 2, 2008 | Reply

    Good presentation for those new to jQuery / ASP.NET AJAX (service proxy calls)! You might also like Rick Strahl’s recent posts on jQuery with WCF. Glad the post led you to something new.

  1. 1 Trackback(s)

  2. May 5, 2008: Fatih Hayrio?lu'nun not defteri » 05 May?s web’den seçme haberler » Javascript, yap?lm??, geçi?, aç?l?r, menü, Ba?lant?, DataGrid, ipuçlar?, olaylar?, Hat?rlatmakta

Post a Comment