Many ways to communicate with your database using jQuery AJAX and ASP.NET

I've recently done a series of articles that feature calling databases via AJAX using jQuery. In pretty much all of the articles, I have used Web Services as my data access mechanism. Judging from the comments that some of the articles have attracted, this has caused a little confusion. But Web Services is just one mechanism. Page Methods and simple ASPX files are two more. And finally, as pointed out by a commenter, Benny Halperin, ASHX files are yet another option. In this article, I shall review each of these approaches.

Each example will feature the same requirement, and that is to obtain and display the Northwind Customer details relating to a specific CustomerID selected from a DropDownList on a page called Customer.aspx.

The bare bones of Customer.aspx are as follows:



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Customer.aspx.cs" Inherits="Customer" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>

</head>
<body>
    <form id="form1" runat="server">
    <div id="SelectCustomers">
      <asp:DropDownList ID="Customers" runat="server">
      </asp:DropDownList>
    </div>
    <div id="CustomerDetails">
    </div>
    </form>
</body>
</html>

This has a code-behind in which the data is obtained and bound to the DropDownList to give the list of customers:



using
System; using System.Data.SqlClient; public partial class Customer : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string connect = "Server=MyServer;Database=Northwind;Trusted_Connection=True"; string query = "SELECT CustomerID, CompanyName FROM Customers"; using (SqlConnection conn = new SqlConnection(connect)) { using (SqlCommand cmd = new SqlCommand(query, conn)) { conn.Open(); Customers.DataSource = cmd.ExecuteReader(); Customers.DataValueField = "CustomerID"; Customers.DataTextField = "CompanyName"; Customers.DataBind(); } } } }

ASPX File

I'll start by saying that this is not something you might see very often. However, I referred to it in one of my first articles on using AJAX and ASP.NET. The aspx page does nothing but communicate with the database and prepare html as a response to the calling code. The page is called FetchCustomer.aspx, and I de-selected the option to use code-behind. This is shown below along with the code:



<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<script runat="server">
  protected void Page_Load(object sender, EventArgs e)
  {
    string connect = "Server=MIKE;Database=Northwind;Trusted_Connection=True";
    string query = "SELECT CompanyName, Address, City, Region, PostalCode," + 
              "Country, Phone, Fax FROM Customers WHERE CustomerID = @CustomerID";
    string id = Request.QueryString["CustomerID"];
    if (id != null && id.Length == 5)
    {
      using (SqlConnection conn = new SqlConnection(connect))
      {
        using (SqlCommand cmd = new SqlCommand(query, conn))
        {
          cmd.Parameters.AddWithValue("CustomerID", Request.QueryString["CustomerID"]);
          conn.Open();
          SqlDataReader rdr = cmd.ExecuteReader();
          if (rdr.HasRows)
          {
            while (rdr.Read())
            {
              Response.Write("<p>");
              Response.Write("<strong>" + rdr["CompanyName"].ToString() + "</strong><br />");
              Response.Write(rdr["Address"].ToString() + "<br />");
              Response.Write(rdr["City"].ToString() + "<br />");
              Response.Write(rdr["Region"].ToString() + "<br />");
              Response.Write(rdr["PostalCode"].ToString() + "<br />");
              Response.Write(rdr["Country"].ToString() + "<br />");
              Response.Write("Phone: " + rdr["Phone"].ToString() + "<br />");
              Response.Write("Fax: " + rdr["Fax"].ToString() + "</p>");
            }
          }
        }
      }
    }
    else 
    {
      Response.Write("<p>No customer selected</p>"); 
    }
    Response.End();
  }
</script>

This file is solely responsible for generating a response to the AJAX call, and presents no UI itself, so using a code-behind page is unnecessary. That's why the file makes use of <script runat="server">. It takes the value passed into the CustomerID querystring value and gets the relevant customer details, and then goes through the fields returned in the DataReader, and Response.Writes the values with a little html mixed in. There are a number of ways that jQuery can request this page and handle the response. The first way to look at is the load() function, which loads html from a remote file:


<script type="text/javascript" src="script/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
  $(document).ready(function() {
    $('#Customers').change(function() {
      $('#CustomerDetails').load("FetchCustomer.aspx?CustomerID=" + $('#Customers').val());
    });
  });

</script>

The code above will go into the head section of Customer.aspx. First, the latest version of the jQuery library is referenced, and then as the page loads - $(document).ready() - a function is applied to the onchange event of the drop down list. This function simply gets the div with the ID of CustomerDetails to load the html returned from FetchCustomer.aspx, and passes the currently selected dropdown list value in the querystring.

An alternative to load() is $.get(). This does exactly the same thing, except that the callback argument specifies what is to be done with the response from the AJAX request. Just replace the javascript code on the head of the Customer.aspx file with the following:


<script type="text/javascript" src="script/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
  $(document).ready(function() {
    $('#Customers').change(function() {
      $.get("FetchCustomer.aspx",
        { CustomerID: "" + $('#Customers').val() + "" },
        function(data) {
          $('#CustomerDetails').html(data);
        });
    });
  });
</script>

Here, the querystring value is passed along with the querystring name in { } brackets, with the name and the value separated by a colon. jQuery takes these values and constructs a querystring as part of the HTTP request, so that the page called is FetchCustomer.aspx?CustomerID=SomeValue. It's interesting to note at this point that if you were to pass the { } brackets into the load method, you would force an HTTP POST request, rather than a GET request. In the $.get() example, the response is available in the variable data and the jQuery html() function is used to place this in the CustomerDetails div.

The final calling method I will look at is the one that I have been using in previous articles: $.ajax(). This is a more feature rich method in that it allows a range of options to be applied to manage different types of call, and error handling. As such, it can (and has - if previous comments are anything to go by) prove a little confusing. Nevertheless, we'll look at its use in the context of the current requirement to call an aspx file:


<script type="text/javascript" src="script/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
  $(document).ready(function() {
    $('#Customers').change(function() {
      $.ajax({
        contentType: "text/html; charset=utf-8",
        data: "CustomerID=" + $('#Customers').val(),
        url: "FetchCustomer.aspx",
        dataType: "html",
        success: function(data) {
          $("#CustomerDetails").html(data);
        }
      });
    });
  });
</script>

Only a limited number of options have been applied in the preceding code, but it's already clear to see that the load() and $.get() alternatives are much simpler to use. We'll use the load() option with the next approach, ASHX files.

ASHX Files

ASHX files are convenient ways to deliver partial content to a web page. They are actually HttpHandlers, and are responsible for processing incoming HTTP requests and providing the appropriate response. Quite often, they are used for delivering binary content such as images, or files that are stored in a database or outside of the web application file system. For delivering small amounts of html to be plugged into a particular position on a web page, they can be extremely useful. Once you have chosen Add New Item -> Generic Handler, you should get a template for a class that inherits from IHttpHandler. It will contain one method - ProcessRequest() and one property - IsReusable(). The logic to render the output will go into ProcessRequest() as follows:


<%@ WebHandler Language="C#" Class="FetchCustomer" %>

using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;

public class FetchCustomer : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/html";
        string connect = "Server=MIKE;Database=Northwind;Trusted_Connection=True";
        string query = "SELECT CompanyName, Address, City, Region, PostalCode," +
                  "Country, Phone, Fax FROM Customers WHERE CustomerID = @CustomerID";
        string id = context.Request.QueryString["CustomerID"];
        if (id != null && id.Length == 5)
        {
          using (SqlConnection conn = new SqlConnection(connect))
          {
            using (SqlCommand cmd = new SqlCommand(query, conn))
            {
              cmd.Parameters.AddWithValue("CustomerID", context.Request.QueryString["CustomerID"]);
              conn.Open();
              SqlDataReader rdr = cmd.ExecuteReader();
              if (rdr.HasRows)
              {
                while (rdr.Read())
                {
                  context.Response.Write("<p>");
                  context.Response.Write("<strong>" + rdr["CompanyName"].ToString() + "</strong><br />");
                  context.Response.Write(rdr["Address"].ToString() + "<br />");
                  context.Response.Write(rdr["City"].ToString() + "<br />");
                  context.Response.Write(rdr["Region"].ToString() + "<br />");
                  context.Response.Write(rdr["PostalCode"].ToString() + "<br />");
                  context.Response.Write(rdr["Country"].ToString() + "<br />");
                  context.Response.Write("Phone: " + rdr["Phone"].ToString() + "<br />");
                  context.Response.Write("Fax: " + rdr["Fax"].ToString() + "</p>");
                }
              }
            }
          }
        }
        else
        {
          context.Response.Write("<p>No customer selected</p>");
        }
        context.Response.End();
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }
}

The method is hardly any different to the ASPX file approach, and the jQuery load() approach is also identical, except for the endpoint it references:


<script type="text/javascript" src="script/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
  $(document).ready(function() {
    $('#Customers').change(function() {
      $('#CustomerDetails').load("FetchCustomer.ashx?CustomerID=" + $('#Customers').val());
    });
  });
</script>

Page Methods

A Page Method is a static method that belongs to its Page class. As such, it can be placed in a <script runat="server"> block, or in code-behind. Since I am already using code-behind to populate the DropDownList on PageLoad() in Customer.aspx, I'll stick with the code-behind approach. ASP.NET 3.5 methods will always serialize and return a JSON object wrapped inside another one: d, if the request contentType is set to application/json.

To add the method to the code behind, two additional references are needed:


using System.Text;
using System.Web.Services;

These will allow me to use a StringBuilder object to build the return value, and to adorn the Page Method with the [WebMethod] attribute. The full method is as follows:


[WebMethod]
public static string FetchCustomer(string CustomerID)
{
  string response = "<p>No customer selected</p>";
  string connect = "Server=MyServer;Database=Northwind;Trusted_Connection=True";
  string query = "SELECT CompanyName, Address, City, Region, PostalCode," +
            "Country, Phone, Fax FROM Customers WHERE CustomerID = @CustomerID";
  if (CustomerID != null && CustomerID.Length == 5)
  {
    StringBuilder sb = new StringBuilder();
    using (SqlConnection conn = new SqlConnection(connect))
    {
      using (SqlCommand cmd = new SqlCommand(query, conn))
      {
        cmd.Parameters.AddWithValue("CustomerID", CustomerID);
        conn.Open();
        SqlDataReader rdr = cmd.ExecuteReader();
        if (rdr.HasRows)
        {
          while (rdr.Read())
          {
            sb.Append("<p>");
            sb.Append("<strong>" + rdr["CompanyName"].ToString() + "</strong><br />");
            sb.Append(rdr["Address"].ToString() + "<br />");
            sb.Append(rdr["City"].ToString() + "<br />");
            sb.Append(rdr["Region"].ToString() + "<br />");
            sb.Append(rdr["PostalCode"].ToString() + "<br />");
            sb.Append(rdr["Country"].ToString() + "<br />");
            sb.Append("Phone: " + rdr["Phone"].ToString() + "<br />");
            sb.Append("Fax: " + rdr["Fax"].ToString() + "</p>");
            response = sb.ToString();
          }
        }
      }
    }
  }
  return response;
}

It's more or less identical to the ASPX version. The jQuery code is too:


<script type="text/javascript" src="script/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
  $(document).ready(function() {
    $('#Customers').change(function() {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: "{ CustomerID: '" + $('#Customers').val() + "'}",
        url: "Customer.aspx/FetchCustomer",
        dataType: "json",
        success: function(data) {
          $("#CustomerDetails").html(data.d);
        }
      });
    });
  });
</script>

The response obtained from this pseudo-Web Service is a serialized JSON object:


{"d":"\u003cp\u003e\u003cstrong\u003eQUICK-Stop\u003c/strong\u003e\u003cbr /
\u003eTaucherstra├če 10\u003cbr /\u003eCunewalde\u003cbr /\u003e\u003cbr /
\u003e01307\u003cbr /\u003eGermany\u003cbr /\u003ePhone: 0372-035188
\u003cbr /\u003eFax: \u003c/p\u003e"}

Unicode escape characters appear in place of non-ASCII characters - principally the "<" (\u003c) and ">" (\u003e) tag characters. As you can see, the html returned from the method is represented as the value of a single property: d. An alternative to returning partial html is to return a custom business object. This is what we will look at next. Within the Customer Page class, I'll define the properties of a Company object:


public class Company
{
  public string CompanyID { get; set; }
  public string CompanyName { get; set; }
  public string Address { get; set; }
  public string City { get; set; }
  public string Region { get; set; }
  public string PostalCode { get; set; }
  public string Country { get; set; }
  public string Phone { get; set; }
  public string Fax { get; set; }
}

This is followed by the revised Page Method which returns a Company object, populated from the DataReader:


[WebMethod]
public static Company FetchCustomer(string CustomerID)
{
  Company c = new Company();
  string connect = "Server=MyServer;Database=Northwind;Trusted_Connection=True";
  string query = "SELECT CompanyName, Address, City, Region, PostalCode," +
            "Country, Phone, Fax FROM Customers WHERE CustomerID = @CustomerID";
  if (CustomerID != null && CustomerID.Length == 5)
  {
    using (SqlConnection conn = new SqlConnection(connect))
    {
      using (SqlCommand cmd = new SqlCommand(query, conn))
      {
        cmd.Parameters.AddWithValue("CustomerID", CustomerID);
        conn.Open();
        SqlDataReader rdr = cmd.ExecuteReader();
        if (rdr.HasRows)
        {
          while (rdr.Read())
          {
            c.CompanyName = rdr["CompanyName"].ToString();
            c.Address = rdr["Address"].ToString();
            c.City = rdr["City"].ToString();
            c.Region = rdr["Region"].ToString();
            c.PostalCode = rdr["PostalCode"].ToString();
            c.Country = rdr["Country"].ToString();
            c.Phone = rdr["Phone"].ToString();
            c.Fax = rdr["Fax"].ToString();
          }
        }
      }
    }
  }
  return c;
}

The result of this call is the object d again, which has one property - another object of type Company:


{"d":{"__type":"Company","CompanyID":null,"CompanyName":"Old World Delicatessen",
"Address":"2743 Bering St.","City":"Anchorage","Region":"AK","PostalCode":"99508",
"Country":"USA","Phone":"(907) 555-7584","Fax":"(907) 555-2880"}}

Since we are no longer returning html, we have to parse the nested object and create the html within the client script:


<script type="text/javascript" src="script/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
  $(document).ready(function() {
    $('#Customers').change(function() {
      $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: "{ CustomerID: '" + $('#Customers').val() + "'}",
        url: "Customer.aspx/FetchCustomer",
        dataType: "json",
        success: function(data) {
          var Company = data.d;
            $('#CustomerDetails').append
              ('<p><strong>' + Company.CompanyName + "</strong><br />" +
              Company.Address + "<br />" +
              Company.City+ "<br />" +
              Company.Region + "<br />" +
              Company.PostalCode + "<br />" +
              Company.Country + "<br />" +
              Company.Phone + "<br />" +
              Company.Fax + "</p>" )
        }
      });
    });
  });
</script>

ASP.NET Web Services

I have already detailed how to use ASP.NET 3.5 Web Services with jQuery in this article, but for completeness, we'll create one here by adding a new item to the project:

And within the file that has just been created, we add a method. Here's the complete code:


<%@ WebService Language="C#" Class="FetchCustomer" %>

using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data.SqlClient;
using System.Text;
using System.Web.Script.Services;


[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[ScriptService]


public class FetchCustomer : WebService
{
  [WebMethod]
  public string GetCustomer(string CustomerID)
  {
    string response = "<p>No customer selected</p>";
    string connect = "Server=MyServer;Database=Northwind;Trusted_Connection=True";
    string query = "SELECT CompanyName, Address, City, Region, PostalCode," +
              "Country, Phone, Fax FROM Customers WHERE CustomerID = @CustomerID";
    if (CustomerID != null && CustomerID.Length == 5)
    {
      StringBuilder sb = new StringBuilder();
      using (SqlConnection conn = new SqlConnection(connect))
      {
        using (SqlCommand cmd = new SqlCommand(query, conn))
        {
          cmd.Parameters.AddWithValue("CustomerID", CustomerID);
          conn.Open();
          SqlDataReader rdr = cmd.ExecuteReader();
          if (rdr.HasRows)
          {
            while (rdr.Read())
            {
              sb.Append("<p>");
              sb.Append("<strong>" + rdr["CompanyName"].ToString() + "</strong><br />");
              sb.Append(rdr["Address"].ToString() + "<br />");
              sb.Append(rdr["City"].ToString() + "<br />");
              sb.Append(rdr["Region"].ToString() + "<br />");
              sb.Append(rdr["PostalCode"].ToString() + "<br />");
              sb.Append(rdr["Country"].ToString() + "<br />");
              sb.Append("Phone: " + rdr["Phone"].ToString() + "<br />");
              sb.Append("Fax: " + rdr["Fax"].ToString() + "</p>");
              response = sb.ToString();
            }
          }
        }
      }
    }
    return response;
  }
}

This method will return the partial html that we have used before, but the main points to note are that the [ScriptService] attribute has been uncommented, which allows Javascript to call the method, and that the method is NOT static (as it must be with the Page Method). The jQuery code is almost the same as with the Page Method approach:

  

<script type="text/javascript" src="script/jquery-1.3.2.min.js"></script>
  <script type="text/javascript">
    $(document).ready(function() {
      $('#Customers').change(function() {
        $.ajax({
          type: "POST",
          contentType: "application/json; charset=utf-8",
          url: "FetchCustomer.asmx/GetCustomer",
          data: "{ CustomerID: '" + $('#Customers').val() + "'}",
          dataType: "json",
          success: function(data) {
            $("#CustomerDetails").html(data.d);
          }
        });
      });
    });
</script>

Summary

We've looked at a number of ways to perform data access within ASP.NET to work with jQuery AJAX: ASPX file, ASHX file, Page Method and Web Service, with a choice of how to call the ASPX file in particular. So which should you use and when?

The ASPX file approach is the one that will be most familiar to developers coming from another technology such as classic ASP or PHP. It also provides easier access, or shorter code with the load() method. Although not shown here, you can also return custom business objects serialized to JSON, and use the getJSON() method that comes with jQuery. This helps to maintain a separation of concerns. To aid this further, there is no reason why you cannot group your ASPX files in a separate folder. They will be accessible to all pages in your application. One final point in favour of the ASPX approach is that you can use an inline coding method to return HTML rather than using Response.Write() to render the output. This again will be most familiar to those migrating from other technologies.

ASHX files are nice and neat. They are more lightweight than ASPX files in that they won't cause an entire Page class to be instantiated on the web server. However, just like ASPX files, each one can only be responsible for one method. If you want overloaded methods, each one will need to be in its own separate file.

Page Methods are great if you don't mind mixing data access with your presentation logic, or want to keep a slimmed down approach with just 2 layers. Ideally they should be placed in the same page where the method is going to be used, and not if they might be needed ny multiple pages. That way may lead to confusion.

Full Web Services are at their most useful when you want to allow other applications to make use of your data access services. They are also a good way to keep clear separation of different functionality within your application, or if you have an aversion to the ASPX file approach. Finally, web services allow multiple related methods to reside in the same place which makes logical grouping and maintenance easier.

Date Posted: Monday, May 4, 2009 6:39 PM
Last Updated: Friday, October 10, 2014 9:07 PM
Posted by: Mikesdotnetting
Total Views to date: 818167

47 Comments

Tuesday, May 5, 2009 5:24 PM - Benny Halperin

Great article!

Question: ASPX is overkill in this case because it contains functionality to support UI elements. In your example ASPX is used merely for delivering data that client code on another page will display. Wouldn't it be better to use a handler (ASHX) for that purpose?

Speaking of which, what is the difference in practice between ASHX and ASMX in your example and in general? When I create an ASHX file in 3.5, the class (inheriting from IHttpHandler) has the [WebService] and [WebServiceBinding] attributes just like ASMX.

Tuesday, May 5, 2009 10:14 PM - Mike

@Benny,

Great point. I completely overlooked HttpHandlers (I don't very often use them), but will modify the article to include them.

As far as the attributes are concerned, I believe that these are only added if you choose to add a Generic Handler to a web *application* or project, and not a Web Site. As for why there is a difference between the two, I have no idea. If anyone has anything to add here, I'd be happy to hear it.

But handlers are not web services. For example, when you create a Web Service, you automatically get the benefit of a Service Description generated by ASP.NET for you. And Web Services will automatically serialize responses as JSON if called by client code.

If you want to provide a service to be used by third parties, you will probably want to return serialized business objects. Web Services make this easy, whereas an HttpHandler needs more work.

Wednesday, May 27, 2009 2:27 AM - Mustafa Kipergil

Jquery, ajax and asp.net ... just like all in one (AIO) package... Thanks a lot great post

Wednesday, June 10, 2009 8:59 PM - infocyde

Great post, I've used all the approaches except the httphandler, with one link I've got three great approaches for jQuery Ajaxifying data with sample code. Great resource. Thanks for sharing.

Thursday, June 18, 2009 2:02 PM - Vinod

This is a great post...
I tried some of it, but i am not able to call page methods or the web service methods..
Below it the code i am been using..

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>

<script type="text/javascript">
$(document).ready(function() {
$('#drpArea').change(function() {
$.ajax({

type: "POST",

url: "Default.aspx/getDate",

data: "{}",

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

dataType: "json",
success:function(data){
alert(data.d);
$("#AreaDetails").html(data.d);
}
});
});
});

</script>

Here is the page method..
[WebMethod]
public static string getDate()
{
return DateTime.Now.ToString();
}


the alert always shows Undefined..
Help me resolve this problem

Friday, June 19, 2009 7:53 AM - Mike

@Vinod,

This is not a question and answer forum. There is a good one at www.asp.net. You should ask questions there. You are likely to get a quicker answer there too. But have you used FireBug or Fiddler to see what your method returns? Did you decorate the Web Service with the ScriptService attribute?

Friday, June 19, 2009 11:26 AM - shabir hakim

Hi,
Great and TRUE Words which really shows how JQuery is implemeted...Tremendous job..keep it up
"Humara tho kaam hein ki jalatay chalay Charaag"
saamemnay dushman ka ghar ho yah dost ka"
bit poetric,if you want to know meaning,let me write two more line
Our Job is to keep lightening the candle of knowledge,let it be our enemy ahead or a friend ...
Thanks

Monday, July 13, 2009 4:02 AM - Hamid

Good article please keep it up to date

Monday, July 13, 2009 4:08 AM - Babu

I guess using a aspx page for a simple DB operation is overhaed when compared to ASHX. Because, ASPX will have its full page life cycle which is not neccessasry in this case. ASHX is the best option in this case.

Correct me if this is wrong...

Monday, July 13, 2009 7:56 AM - Mike

@Babu

I believe that is what I said in the article:

"ASHX files are nice and neat. They are more lightweight than ASPX files in that they won't cause an entire Page class to be instantiated on the web server."

Monday, July 13, 2009 9:01 AM - Cyril Gupta

Excellent article Mike. Would you believe it I was thinking just yesterday that there ought to be something like this.

Cheers!

Monday, July 13, 2009 11:25 AM - vikas dhiman

Page Methods do not load the whole aspx page.
window.onload and widow.unload DOM events are not raised with Async requests.

So this is not an overkill.

Monday, July 13, 2009 12:07 PM - Mike

@Vikas

I can't see anywhere in the article or the comments so far where anyone has suggested that Page Methods are overkill, or load an entire page. Benny suggested that using an ASPX file solely to render a response incurs an overhead, but that's not the same as a Page Method.

Monday, July 13, 2009 6:26 PM - Vikas Dhiman

One of the comments questioned page method approach as overkill, this one:
"05 May 2009 17:24 from Benny Halperin
Question: ASPX is overkill in this case because it contains functionality to support UI elements. In your example ASPX is used merely for delivering data that client code on another page will display. Wouldn't it be better to use a handler (ASHX) for that purpose?"

I was just clarifying that. Cheers!

Tuesday, July 14, 2009 3:31 AM - J Walia

which one is the best method??

Tuesday, July 14, 2009 4:14 AM - Pablo

This code has many of old ASP 3.0 coding style with jQuery ingredient.

Tuesday, July 14, 2009 7:18 AM - Qureshi

Dear Mike,

Thank you for your such valuable article,
also can you please attach a zip file to downlaod code.

its help reader a lot.

like me :)

Tuesday, July 14, 2009 10:30 AM - deef

Nice article.
Personally I think that using ASPX or ASHX is bad practice. Sure it's fast and easy, but so was classic ASP, if you get my point.
I'm more a fan of the PageMethods and even more of the WebService approach.

Tuesday, July 14, 2009 2:31 PM - Mike

@J Walia

Which one is the "best" method? That depends....

Tuesday, July 14, 2009 2:33 PM - Mike

@deef

I wouldn't agree with a blanket statement such that ASHX is "bad practice". I think they have their place. Because a page method is tied to the page that it resides in, some might consider that bad practice too. Hopefully, I have given enough information in the article for people to decide which is the most suitable approach given their requirement.

Wednesday, July 15, 2009 12:36 PM - sjb101

Great article.... For the sake of completeness perhaps this article should include ajax enabled WCF an example is shown here.

http://msdn.microsoft.com/en-us/library/bb924552.aspx

Wednesday, July 15, 2009 1:26 PM - Mike

@sjb101,

Thanks for your suggestion. I will be doing something on WCF in the very near future.


Tuesday, October 6, 2009 2:23 AM - Iyyappan.S

its really very very nice coding....
and easily understand
thanks...

Wednesday, December 2, 2009 7:52 AM - Byku

This is a great post...

Wednesday, January 27, 2010 4:59 PM - Pragnesh Sharma

gr8 Article

Thursday, February 4, 2010 4:28 AM - amarjit

anyone have solution of my problem

i am using a file upload on a page.. and i want is that when i choose fie it should be uploaded and saved immediately and shown on the page in img tag..
with no postback at all


Thursday, February 4, 2010 8:16 PM - Mike

@amarjit

This isn't a forum, and your question has nothing to do with the topic of the article.

Friday, April 23, 2010 4:31 AM - Kevin

Many thanks! great tutorial, have been looking for this for a long time!!!!!

Tuesday, May 11, 2010 5:07 PM - Billy Blackerby

Great article, thanks for clearly demonstrating the various methods.

Thursday, May 20, 2010 1:48 AM - Venkat N

Awesome article !!! One of the best that I've read in recent past...kudos !!!

Tuesday, July 6, 2010 11:23 AM - venkatx5

It's a Great Post I must say. I am very Interested in JQuery and google took me here which is the right place where I got what I want.. Thanks Mike.

Wednesday, August 4, 2010 7:15 PM - AKSharePoint

Fantastic work Mike!

To keep everything packaged and performing single click deployments web services become impractical. That leaves ASPX file, ASHX file, and Page Method. I go with the ashx file because it seems like a more natural fit.

Tuesday, November 16, 2010 4:16 PM - Haroon

Awsome article , great explanation thankx.

Friday, February 25, 2011 7:51 PM - John

Thanks for the helpful information here Mike. I've used this article a number of times to get more grounded in using jQuery and Ajax.

I typically set up my ASPX pages to use jQuery which call Web Methods using AJAX to retrieve presentation data. I love the speed and lack of postback to alter the UI. However, this does mix data and presentation, which I would like to stay away from. Also, I use the same Web Methods on different pages, which I would also like to stay away from. Is there a way to centralize the Web Method functionality so I don't have to keep rewriting the code on each page. I thought of creating an ASHX with all of the web methods? Not sure that is possible. Just wanted to get some feedback on how to write reusable code and maintain ithe separation of data and presentation.

Thanks again for the helpful information.

Friday, February 25, 2011 8:07 PM - Mike

@John,

You want to steer clear of using HttpHandlers to return varying results based on parameters (querystring values). Ideally, you should set up a Web or WCF Service, and use that to expose multiple methods.

Monday, March 14, 2011 9:58 AM - abhinav

nice one

Friday, March 23, 2012 11:23 AM - mostafa

very good, thank you ,i am view your site for first time and love this site in first view

Monday, December 31, 2012 6:06 AM - Shahnoor Shaikh

Awesome Article Mike!!!

Friday, February 8, 2013 7:49 PM - dan

Great article, just the info I was looking for! Thank you!

Monday, March 18, 2013 1:41 PM - Matt

Nice article. Can you update it to include a Web API example?

Monday, March 25, 2013 11:51 AM - Raguraman

Hi,
Can i get the same process code in jsp. Because this code i am developing a project which is related to this.

Thank u in advance.......

Monday, March 25, 2013 12:39 PM - Mike

@Raguraman,

No. Not here.

Friday, June 7, 2013 1:38 PM - John

Thanks for putting together this article that shows each of the approaches when working with AJAX. I have a Websites that multiple users can access simultaneously. Which method is best to use in this environment?

Wednesday, July 10, 2013 1:16 PM - SA

Hi, Great article!
What about the (not so) new MVC4 web API ?
It wasn't available when this article was posted but i see that you did update it in the past.
It can be a great addition that will than cover all the options that available now.

Thank for this article.

Monday, October 14, 2013 5:21 AM - arvind

good

Friday, October 18, 2013 4:09 PM - Mahidi

Great article! Thanks

Friday, May 30, 2014 4:00 AM - prabhakar

Very good article
Add your comment

If you have any comments to make about this article, please use this form to do so. Make sure that your comment relates specifically to the article above. More general comments can be posted through the form on the Contact page.

Please note, all comments are moderated, and some may not be published. The kind of things that will ensure your comment is deleted without ever seeing the light of day are as follows:

  • Not relevant to the article
  • Gratuitous links to your own site or product
  • Anything abusive or libellous
  • Spam
  • Anything in a language I don't understand including gibberish.

I do not pass email addresses on to spammers, so a valid one will assist me in responding to you personally if required.

Recent Comments

Allen Michaels 12/17/2014 4:37 PM
In response to Cascading DropDownLists with jQuery and ASP.NET
Fantastic thank you so much!...

Emily 12/17/2014 12:36 PM
In response to Parameterized IN clauses with ADO.NET and LINQ
Thanks, very helpful!!!! Can i use this for multiple in's ????? IN (.....) and IN(...) and IN...

sss 12/16/2014 3:06 PM
In response to Solving the Operation Must Use An Updateable Query error
good...

Gjuro 12/15/2014 10:30 PM
In response to Examining the Edit Methods and Edit View
You have one fromr (and it should be from, I suppose). :-)...

Gjuro 12/15/2014 10:27 PM
In response to Adding Search
Hi, thnx for all this C#->VB translations. Yet, the following code block is (slightly) in error it a...

Scot 12/14/2014 1:39 PM
In response to Entity Framework 6 Recipe - Alphabetical Paging In ASP.NET MVC
Thanks,Mike I found solution....

Gjuro 12/13/2014 10:52 PM
In response to Accessing Your Model's Data from a Controller
The article mentions "Creating an Entity Framework Data Model for an ASP.NET MVC Application" (at is...

Samuel 12/13/2014 8:40 AM
In response to Displaying The First n Characters Of Text
I have failed to use the extension because it throws an error that it doesn't recognise the chop be...

Ignas 12/12/2014 5:11 PM
In response to Cleaner Conditional HTML Attributes In Razor Web Pages
Any suggestions for Html Helper elements with HtmlAttributes, when you need to conditionally set it...

Gautam 12/11/2014 8:50 PM
In response to Validation In Razor Web Pages 2
Hi Mike Is this required for V3, non html helper input...