Using jQuery to Call ASP.NET AJAX Page Methods – By Example

A commenter recently requested a more in-depth sample demonstrating the technique I used in my Using jQuery to Call ASP.NET AJAX Page Methods post. He wanted to see how you could use jQuery to send the contents of a GridView row to a WebMethod page.

Here are the steps:

  • Create template columns in the GridView and wrap the data you want to send to the server in some sort of tag that you can access via JavaScript
  • Create a link that calls the JavaScript function that extracts the data and prepares it for the Ajax request

The most interesting lines of code really are lines 41 – 45 of the ASPX markup. These lines are where the script formats the variables appropriately to use the CallPageMethod function that uses jQuery to call the page’s WebMethod.

The ASPX Markup

   1:  <%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridView.aspx.cs" Inherits="Test_GridView" %>
   2:   
   3:  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   4:   
   5:  <html xmlns="http://www.w3.org/1999/xhtml">
   6:  <head runat="server">
   7:      <title></title>
   8:      <style type="text/css">
   9:      .none {display:none;}
  10:      </style>
  11:      <script src="../jquery-1.2.6.min.js" type="text/javascript"></script>
  12:      <script type="text/javascript">
  13:      function CallPageMethod(methodName, onSuccess, onFail) {
  14:          var args = '';
  15:          var l = arguments.length;
  16:          if (l > 3) {
  17:              for (var i = 3; i < l - 1; i += 2) {
  18:                  if (args.length != 0) args += ',';
  19:                  args += '"' + arguments[i] + '":"' + arguments[i + 1] + '"';
  20:              }
  21:          }
  22:          var loc = window.location.href;
  23:          loc = (loc.substr(loc.length - 1, 1) == "/") ? loc + "default.aspx" : loc;
  24:          $.ajax({
  25:              type: "POST",
  26:              url: loc + "/" + methodName,
  27:              data: "{" + args + "}",
  28:              contentType: "application/json; charset=utf-8",
  29:              dataType: "json",
  30:              success: onSuccess,
  31:              fail: onFail
  32:          });
  33:      }
  34:   
  35:      function select(index) {
  36:          var id = $("#id" + index).html();
  37:          var title = $("#ttl" + index).html();
  38:          var author = $("#auth" + index).html();
  39:          var pubDate = $("#pubDate" + index).html();
  40:   
  41:          CallPageMethod("SelectBook", success, fail,
  42:              "id",id,
  43:              "title",title,
  44:              "author",author, 
  45:              "publishDate",pubDate);
  46:      }
  47:      
  48:      function success(response)
  49:      {
  50:          alert(response.d);
  51:      }
  52:      
  53:      function fail(response)
  54:      {
  55:          alert("An error occurred.");
  56:      }
  57:      </script>
  58:  </head>
  59:  <body>
  60:      <form id="form1" runat="server">
  61:      <asp:GridView 
  62:          ID="gv" 
  63:          runat="server" 
  64:          AutoGenerateColumns="False">
  65:          <Columns>
  66:              <asp:TemplateField HeaderText="Select">
  67:                  <ItemTemplate>
  68:                      <a href="javascript:void(0);" onclick="select(<%= this.index.ToString() %>);">Select</a>
  69:                  </ItemTemplate>
  70:              </asp:TemplateField>
  71:              <asp:TemplateField HeaderText="Title">
  72:                  <ItemTemplate>
  73:                      <span id="id<%= this.index.ToString() %>" class="none"><asp:Literal ID="id" 
  74:                          Text='<%# Bind("ID") %>' runat="server" /></span>
  75:                      <span id="ttl<%= this.index.ToString() %>"><asp:Literal ID="ttl" 
  76:                          Text='<%# Bind("Title") %>' runat="server" /></span>
  77:                  </ItemTemplate>
  78:              </asp:TemplateField>
  79:              <asp:TemplateField HeaderText="Author" SortExpression="Author">
  80:                  <ItemTemplate>
  81:                      <span id="auth<%= this.index.ToString() %>"><asp:Literal ID="author" 
  82:                          Text='<%# Bind("Author") %>' runat="server" /></span>
  83:                  </ItemTemplate>
  84:              </asp:TemplateField>
  85:              <asp:TemplateField HeaderText="Publish Date" SortExpression="PublishDateShort">
  86:                  <ItemTemplate>
  87:                      <span id="pubDate<%= this.index.ToString() %>"><asp:Literal ID="dt" 
  88:                          Text='<%# Bind("PublishDateShort") %>' runat="server" /></span>
  89:                      <% this.index++; %>
  90:                  </ItemTemplate>
  91:              </asp:TemplateField>
  92:          </Columns>
  93:      </asp:GridView>
  94:      </form>
  95:  </body>
  96:  </html>

The Codebehind

   1:  using System;
   2:  using System.Web.Services;
   3:   
   4:  public partial class Test_GridView : System.Web.UI.Page
   5:  {
   6:      protected int index = 0;
   7:   
   8:      protected void Page_Load(object sender, EventArgs e)
   9:      {
  10:          if (!this.Page.IsPostBack)
  11:          {
  12:              this.gv.DataSource = BookRepository.Instance.GetBooks(5);
  13:              this.gv.DataBind();
  14:          }
  15:      }
  16:   
  17:      [WebMethod]
  18:      public static string SelectBook(int id, string title, 
  19:          string author, DateTime publishDate)
  20:      {
  21:          string msg = string.Format("You selected \"{0}\" by {1} " +
  22:              "published on {2}.",
  23:              title, author, publishDate.ToShortDateString());
  24:          return msg;
  25:      }
  26:  }

9 Comments

  • Hi Craig, the post is very interesting, i need to know if i can use a methods from a page with HTTPS protocol

  • This is the best post I've seen on jQuery and pageMethods so far. Thanks!

  • @briandus: thanks!

    @Lucas: as long as you are serving your via https and making calls back to the server under a https context, then everything should work fine. jQuery is just a standard JavaScript file...

  • $.ajax({

    25: type: "POST",

    26: url: loc + "/" + methodName,

    27: data: "{nameoftheid" + args + "}",

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

    29: dataType: "json",

    30: success: onSuccess,

    31: fail: onFail

    32: });

  • naming each parameter in the page method signature seems a little fragile.

    is there a way to pass in the entire json object and just parse it out server side?

    am i missing something?

  • Hi Sir,

    I enjoyed the article very much but was little confused with the CallPageMethods internals. I would appreciate if you could please explain the code briefly i.e a clear explanation of the code would prove better for beginners too.

    Thanks & Regards,
    Santosh

  • Hi Sr, thanks for your example. I follow your example exactly, but when I run the sample and click the "Select" column the jquery post does not make anything, the events success/fail does not fire.
    What am I doing wrong?

    Regards.

  • Hello Sir,
    This is very interesting example.I enjoy it and also applied it in one of my application.
    Thanks & regards,
    Rakesh Kumar

  • Thank you very much. This example is so much helpful for me. I have enjoyed your example.

Comments have been disabled for this content.