JQuery: Consuming Page Method in ASP.Net

jquery1

Introduction: Page Method is an easy way to communicate with the code behind and JQuery functions for simple operations. Although it can be done using web services or WCF but, for simple operations there is no need to complicate things. This post is a simple demo of how we can consume page methods in ASP.Net using AJAX. Note: This example produces summation of two inputted integers as result and I know in real life this logic is not going to help you but, as I already said my intention is to show only a way to consume page methods with JQuey using AJAX so, you can definitely replace your logic here.

Demo:
1. Place two Textbox(ID: txtNum1, txtNum2) and a Button (ID: btnSum) in the page.

<div>Enter two integers and click <strong>SUM</strong> button to get the result
<div style="padding: 5px;">First Number</div>
<div style="padding: 5px;">Second Number</div>
</div>

2. Create a page method (SumIntegers()) in code behind with two integer parameters named num1 and num2. Don’t forget to assign [WebMethod()] attribute to it for which you need to add namespace System.Web.Services and to call the page method directly make it static.

using System;
using System.Web.Services;

public partial class WebMethodDemo : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e){}

    [WebMethod()]
    public static int SumIntegers(int num1, int num2)
    {
        return num1 + num2;
    }
}

3. Now the last thing to do is to write the JQuery section where we will be able to call the ajax method to get the desired result.

<script type="text/javascript">// <![CDATA[
        $(document).ready(function () {
            $("#btnSum").click(function (e) {

                var num1 = $("#txtNum1").val();
                var num2 = $("#txtNum2").val();
                $.ajax({
                    type: "POST",
                    url: window.location.href + "/SumIntegers",
                    data: '{"num1":"' + num1 + '","num2":"' + num2 + '"}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {
                        alert(num1+"+"+num2+"="+msg.d);
                    },
                    error: function () {
                        alert("Error occured. Please check inputs !");
                    }
                });
            });
        });

// ]]></script>

Explanation: As you may know, $(document).ready() function gets executed as soon as DOM is loaded and before the page contents are rendered in to the browser. We need to embed all the JQuery markup inside this function. Define an event handler for click event of button ‘btnSum’. Rest of the logic is written inside this event handler as we want to execute our logic on clicking the button. First retrieve the values from the textboxes. Now to perform the asynchronous HTTP(ajax) request, call the .ajax() method of JQuery with the url and necessary settings. If the ajax call succeeds then we can get the returned result using msg.d as the result will always be enclosed within the ‘d’ (since ASP.Net 3.5, which prevents direct execution of the string as script).

Downloads: Demo Project Download

I hope this is useful.

Thanks for reading and please don’t forget to add a comment.

About these ads

4 thoughts on “JQuery: Consuming Page Method in ASP.Net

  1. Thanks for helpful post. I’m pleased confident this post helps me conserve many hours of searching other related posts simply to find what I was looking for. Merely I want to declare: Thank you!

  2. Pingback: Homepage

  3. Interesting post, it has been a great approach since ASP DOT NET. Page Methods are static they do not need the page instance to work. DOT NET AJAX Page Methods are a hidden feature of DOT NET and a lot of people do not use them but at present the DOT NET development training is special because this platform provides great resources.

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