Directory Freebies VS CheatSheet Forum

RSS

Email

Translate

Home About Archive Privacy Contact Advertise Write for Dev102
Posted by Shahar A on Apr 30th, 2008 | Filed under ASP.Net, Web Development |

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…

Tags: , , , , ,

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


  1. Kevin Deenanauth Said on Apr 30, 2008 :

    Great work!

  2. superjason Said on Apr 30, 2008 :

    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. Joel Said on Apr 30, 2008 :

    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. Shahar A Said on Apr 30, 2008 :

    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. Darrell Said on May 1, 2008 :

    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. Daniel Said on May 2, 2008 :

    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.

  7. vvvlad Said on Jul 28, 2008 :

    Thanks for a great article!

    One question…
    How do you pass a parameter to the webmethod?

  8. Amit Said on Jul 28, 2008 :

    @ vvvlad

    Like what?

    Most parameters you will need are available to you at the code behind.

  9. vvvlad Said on Jul 28, 2008 :

    Hi,
    I have already found a solution for my question.
    You call your webmethod without any parameters from client side.
    If you would define something like this:
    [WebMethod(true)]
    public static MethodReturnedValue SomeMethod(string someParam)
    then you would call it this way:
    PageMethods.SomeMethod(param, callback_success, callback_timeout, callback_error);

  10. Kel Said on Nov 10, 2008 :

    Are u using .NET 2.0 or 3.5? I’m using 2.0 and i get an error using your exact code.

    MethodReturnedValue.Time.get’ must declare a body because it is not marked abstract or extern

  11. Amit Said on Nov 11, 2008 :

    @ Kerl

    We are using ASP.NET 3.5 with Visual Studio 2008

    What are your settings?

  12. Kel Said on Nov 11, 2008 :

    @Amit

    ASP.NET 2.0 with VS ‘05. I’ve noticed alot of tuturials on how to do this but a majority of the sites don’t specify what version of the .NET framework they are using. It seems like something changed from the 2.0 to 3.5 frameworks in regards to the [WebMethods].

  13. Jabber Said on Dec 18, 2008 :

    I found a similar method for ext js at http://www.dottostring.com/2008/12/on-demand-paging-using-extjs-grid-with-client-centric-asp-dot-net-ajax-webmethods/ if anyone is interested.

  14. Jim Said on Nov 4, 2009 :

    Sorry, this is misleading - you haven’t called the webmethod with jquery, you’ve done it with ASP.NET AJAX…

2 Trackback(s)

  1. 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
  2. Jul 22, 2008: ADD JQUERY INTELLISENSE TO YOUR VISUAL STUDIO | Dev102.com

Post a Comment

Write Article for Dev102

Write for Dev102!

We pay for user submitted tutorials and articles that we publish. Anyone can send in a contribution

Learn More