More ASP.NET PageMethods with jQuery and JSON

The PageMethod is a static method in an ASPX page codebehind that is decorated with the WebMethod attribute. This can be called from external client code via the url "PageName.aspx/MethodName". Using jQuery's $ajax function is probably the easiest way to make these calls,although they can also be called via Microsoft AJAX and by other means. Here we provide three examples of PageMethods, of increasing complexity, and show how to set up each PageMethod, as well as how to consume and display

First we need to prepare our Page by inserting a script reference to the latest jQuery CDN:

   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

   Next I'll show the entire jQuery $ajax implementation, with one function for each of the three methods:


     <script>
          $(document).ready(function () {
              // Add the page method call as an onclick handler for the Result div.
              $("#Result").click(function () {
                  $.ajax({
                      type: "POST",
                      url: "Default.aspx/GetDate",
                      data: "{}",
                      contentType: "application/json; charset=utf-8",
                      dataType: "json",
                      success: function (msg) {
                          // Replace the div's content with the page method's return.
                          $("#Result").text(msg.d);
                      }
                  });
              });

              
              $("#Result2").click(function () {
                  $.ajax({
                      type: "POST",
                      url: "Default.aspx/AddNumbers",
                      data: "{a:6, b:9}",
                      contentType: "application/json; charset=utf-8",
                      dataType: "json",
                      success: function (msg) {                           
                          $("#Result2").text(msg.d);
                      }
                  });
              });

            
              $("#Result3").click(function () {
                  $.ajax({
                      type: "POST",
                      url: "Default.aspx/GetFeed",
                      data: "{}",
                      contentType: "application/json; charset=utf-8",
                      dataType: "json",
                      success: function (msg) {
                          var output = "<ul>";
                          var i = 0;
                          for (i = 0; i < msg.d.length; i++) {
                              output = output + "<li><a href=" + msg.d[i].Link + " target='_blank'>" + msg.d[i].Title + "</a></li>";
                          }
                          output = output + "</ul>";
                          $("#Result3").html(output);
                      }
                  });
              });
          }); // end $document.ready
      </script>


     Finally, in our ASPX page markup, we define three DIVs:

<form id="form1" runat="server">
    <div>
    <body>
  <div id="Result">Click here for date and time.</div>

  <div id="Result2">Click here to add 6 and 9.</div>

   <div id="Result3">Click here to see feed summary with links.</div>
</body>
    </div>
</form>


Now let's switch over to the server - side of the Page and complete the code:

        [WebMethod(true)]
        public static string GetDate()
        {
            return DateTime.Now.ToString();
        }

        [WebMethod(true)]
        public static int  AddNumbers(int a, int b)
         {
             return a + b;
        }


        [WebMethod(true)]
        public static List<FeedItem > GetFeed()
        {
            WebClient wc = new WebClient();
            string result =
                 wc.DownloadString(
                      "http://www.eggheadcafe.com/rss.xml");
            wc.Dispose();
           var x=  XElement.Parse(result);
            var l = x.Descendants("item");
           List<FeedItem> list = new List<FeedItem>();
            foreach (var k in l)
            {
                string title = k.Elements("title").FirstOrDefault().Value;
                string link = k.Elements("link").FirstOrDefault().Value;
                FeedItem fi = new FeedItem() {Title =title, Link =link};
               list.Add(fi);
            }
            return list;
        }



In another class file, I've defined a simple  class to hold the feed item title and link elements:

  public class FeedItem
    {
         public string Title { get; set; }
        public string Link { get; set; }
    }

We will  populate a List<FeedItem> of these in the third Webmethod that gets an RSS feed and return it as legal JSON.

Switching back to the client side, here are the methods again:

The first $ajax call gets the date and time from the GetDate() server-side PageMethod:

   $("#Result").click(function () {
                  $.ajax({
                      type: "POST",
                      url: "Default.aspx/GetDate",
                      data: "{}",
                      contentType: "application/json; charset=utf-8",
                      dataType: "json",
                      success: function (msg) {
                          // Replace the div's content with the page method's return.
                          $("#Result").text(msg.d);
                      }
                  });
              });

The type is POST, the url is simply the page name plus a slash/ and the method name. We're specifying contenttype as application/json with charset=utf-8. This is what tells the PageMethod how to return it's result.

The datatype is json, but in this case we aren't transmitting any data in the POST. We define a success: function that takes the received msg object and assigns it to the text property of the Result DIV. The "msg.d" is a feature of Microsoft - specific webmethods; it is a basic security feature.


The second method, which adds two numbers:


     $("#Result2").click(function () {
                  $.ajax({
                      type: "POST",
                      url: "Default.aspx/AddNumbers",
                      data: "{a:6, b:9}",
                      contentType: "application/json; charset=utf-8",
                      dataType: "json",
                      success: function (msg) {
                          // Replace the div's content with the page method's return.
                          $("#Result2").text(msg.d);
                      }
                  });

Note above that the only major difference here is that we are specifying the named parameters in the data: element. This must be legal JSON, which looks like   data: "{a:6, b:9}".


Finally in the third method we do a little HTML creation:

$("#Result3").click(function () {
                  $.ajax({
                      type: "POST",
                      url: "Default.aspx/GetFeed",
                      data: "{}",
                      contentType: "application/json; charset=utf-8",
                      dataType: "json",
                      success: function (msg) {
                          var output = "<ul>";
                          var i = 0;
                          for (i = 0; i < msg.d.length; i++) {
                              output = output + "<li><a href=" + msg.d[i].Link + " target='_blank'>" + msg.d[i].Title + "</a></li>";
                          }
                          output = output + "</ul>";
                          $("#Result3").html(output);
                      }
                  });
              });

Here we are getting back a List<FeedItem> in JSON format, so we iterate over the items collection and construct some <A HREF links comprising the Links and the Titles of each feed entry from our stock eggheadcafe.com RSS  feed.

One thing to note about PageMethods. Since they must be static, an instance of the Page class with all of it's events and access to controls is never created.  All you get is the results of your PageMethod. The contenttype header of the Request as specified in the $ajax call is what determines how the response is formatted. No "JSONification" is required server-side. You can also use PageMethods to insert or update data in your database. You simply make an $ajax POST as shown in the second WebMethod and collect your parameters inside the method body.

You can download the complete Visual Studio 2010  solution  here.

By Peter Bromberg   Popularity  (5905 Views)