CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Using JQuery in ASP.Net AJAX Applications – Part 2

By Satheesh Babu
Posted On Feb 02,2009
Article Rating:
Be first to rate
this article.
No of Comments: 10
Category: ASP.Net AJAX
Print this article.

Using JQuery in ASP.Net AJAX Applications – Part 2

 

In Part 1, we have seen how to make AJAX calls through POST and GET method using JQuery library. Part 1 also discussed about how to integrate and use JQuery intellisense in Visual studio 2008. Moving forward, in Part 2 of this article series, we will see some of the advanced usages of JQuery in ASP.Net AJAX application. We will use the same example which we took to explain the Part 1 of this article. In Part 1, we have implemented the server side functionality using a separate aspx page and it is called through the AJAX methods available in JQuery. This aspx page once called will do a Response.Write() of the result which is captured and displayed to the client using JQuery.  But, the same functionality can be very well implemented through a mere server side function instead of a separate page.

In other words, we can implement the same function through the PageMethods available in ASP.Net AJAX and call it from JavaScript.

To implement the requirement through PageMethods, we need to define a function in codebehind and decorate it with an attribute called WebMethod. To call this PageMethods from JavaScript, we need to enable the EnablePageMethods property of ScriptManager to true. This will create a JavaScript proxy for all the page methods declared in the page and it will be injected to the client side.

 In this article, we will implement same example through PageMethods and we will consume this page methods through JQuery instead of ScriptManager.

 

Implementing PageMethods in ASP.Net AJAX

The page methods should be defined as a public static method and it should be decorated with WebMethod attribute. Refer the below page method that returns a string of available number of tickets at that moment.

 

public partial class _Default : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

     

    }

    [WebMethod]

    public static string GetAvailableTickets()

    {

        int NoOfTicketsAvailable = 5;

        return NoOfTicketsAvailable.ToString();

    }

}

 

Include System.Web.Services namespace for the above web method to work.

 

Calling the PageMethod using JQuery

We can use JQuery.ajax() method to call the PageMethod from client side,

 

<script src="_scripts/jquery-1.2.6.js" type="text/javascript"></script>

        <script language="javascript">

            $(document).ready(function() {

                $("#txtNoOfTickets").blur(function() {

                    var ticketRequired = this.value;

                    var options = {

                        type: "POST",

                        url: "Default.aspx/GetAvailableTickets",

                        data: "{}",

                        contentType: "application/json; charset=utf-8",

                        dataType: "json",

                        success: function(response) {

var avilabletic = parseInt(response.d);                           

                            if (ticketRequired > avilabletic) {

                                alert("Only " + response.d + " tickets available!");

                            }

                            else {

                                alert(response.d);

                            }

 

                        }

                    };

                    //Call the PageMethods

                    $.ajax(options);

 

                });

            });

        </script>

 

<form id="form1" runat="server">

        <asp:TextBox ID="txtNoOfTickets" runat="server"></asp:TextBox>

</form>

 

As I have said earlier, the JQuery.ajax() method will use JSON to communicate to the server. This method will return the number of tickets available at that moment. In this example, I have hard-coded the available number of tickets. You can replace this value from the one got from the database.

 

Download the source code attached in the download section of this article.

 




Calling PageMethods with parameters

The code in previous section discussed about calling a page method without passing parameters. In this section, we will see how to call PageMethods with parameters.

We will have 2 PageMethods, one will check for available number of tickets for males and the other will check for the available number of tickets for females.

 

Codebehind

public partial class CallServerWithParameters : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

 

    }

    [WebMethod]

    public static string GetAvailableTicketsForMales(int no)

    {

        string result = "";

        int NoOfTicketsAvailable = 5;

        if (no > NoOfTicketsAvailable)

        {

            result = "Only " + NoOfTicketsAvailable.ToString() + " Male ticket(s) avaialable. Please enter a lower number!";

        }

        return result;

    }

    [WebMethod]

    public static string GetAvailableTicketsForFemales(int no)

    {

 

        string result = "";

        int NoOfTicketsAvailable = 5;

        if (no > NoOfTicketsAvailable)

        {

            result = "Only " + NoOfTicketsAvailable.ToString() + " Female ticket(s) avaialable. Please eneter a lower number!";

        }

        return result;

    }

}

ASPX

<script src="_scripts/jquery-1.2.6.js" type="text/javascript"></script>

        <script language="javascript">

            $(document).ready(function() {

                $("#txtNoOfMales").change(function() {

                    var ticketRequired = this.value;

                    var options = {

                        type: "POST",

                        url: "CallServerWithParameters.aspx/GetAvailableTicketsForMales",

                        data: "{no:" + ticketRequired + "}",

                        contentType: "application/json; charset=utf-8",

                        dataType: "json",

                        success: function(response) {

                            if (response.d != "") {

                                alert(response.d);

                                $("#txtNoOfMales").focus();

                            }

                        }

                    };

                    //Call the PageMethods

                    $.ajax(options);

 

                });

 

                $("#txtNoOfFemales").change(function() {

                    var ticketRequired = this.value;

                    var options = {

                        type: "POST",

                        url: "CallServerWithParameters.aspx/GetAvailableTicketsForFemales",

                        data: "{no:" + ticketRequired + "}",

                        contentType: "application/json; charset=utf-8",

                        dataType: "json",

                        success: function(response) {

                            if (response.d != "") {

                                alert(response.d);

                                $("#txtNoOfFemales").focus();

                            }

                        }

                    };

                    //Call the PageMethods

                    $.ajax(options);

 

                });

 

            });

        </script>

 

<div>

    No of Male Tickets:<asp:TextBox ID="txtNoOfMales" runat="server"></asp:TextBox>

    No of Female Tickets:<asp:TextBox ID="txtNoOfFemales" runat="server" ></asp:TextBox>

    </div>

 

The above code will alert the user with a message if they enter number of ticket more than the tickets available in that moment. For easy understanding, I have hard-coded the number of tickets available in the PageMethods.

 

Downloads

Download Source 

Conclusion

We have seen how to implement AJAX application with the help of JQuery in Part 1 of this article while the part 2 discussed on how to call a PageMethod using JQuery.  Download the source code attached with this article. Moving forward, we will see more about JQuery and its usages in web development in future article series.

Happy Coding!

 

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
RE:more help
Hi kaushik,
You may be getting the issue when adding the events from ajax postback.
The below link may help you,
http://www.codedigest.com/CodeDigest/60-Dynamically-Adding-JavaScript-in-ASP-Net-AJAX.aspx
http://encosia.com/2009/03/25/document-ready-and-pageload-are-not-the-same/
more help
hi,
i m using update panel in which i m using jQuery but when other control 's event fire it's stop working ,
but again when i refresh page it's works untill other event not fire
aa
dd
Varun
Nice 1
RE:not work on webservice
Hi ming,

Good to know that it worked now..Thanks for reading the article...
not work on webservice
It work now, sorry about that i wrote too much.

i delete "static" keyword on web service is work!

your code is excellent~ because i facing a strange problem.

I post on
http://forums.asp.net/p/1404037/3049238.aspx

but now, solved by your sample~!
not work on webservice
Below is my web service
======================================

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {

[WebMethod]
public static string GetAvailableTickets()
{
int NoOfTicketsAvailable = 5;
return NoOfTicketsAvailable.ToString();
}

}
not work on webservice
But i copy and paste
GetAvailableTickets() to WebService.asmx
and change :
url: "WebService.asmx/GetAvailableTickets",

it not work, do you know why??
thanks you
RE:why not asmx?
Hi ming,
You can make the above method in asmx service! This article explains how to utillize the pagemethods from jQuery...
why not asmx?
I just wonder why put web method to aspx ,not asmx?
is it because it need to be static?