AJAX the easy way in ASP.NET Web Forms using genric handlers
Posted in C#, jQuery, ASP.NET, .NET by Branislav Abadjimarinov on 3/26/2010 12:15:00 AM - CSTIn this article we'll see a quick and elegant ajax call solution
based on generic handlers in asp.net and jQuery. The goal is to
populate a street list in a dropdown with ajax call based on a
selected postal code in a dropdown. The usual way to do this in
ASP.NET Web Forms will be to use the AjaxToolkit, MS Ajax library
and web service. The problem with this approach is that it is
coplex and prone to errors.
To accomplish the task we will create a generic handler(.ashx
file) in our asp.net project. The generic handler is a lightweight
approach to deliver content to the user. It doesn't have the heavy
page lifecycle. By default the generic handler has only one method
- ProcessRequest and one readonly property - IsReusable. The
handler inherits directly from IHttpHandler. The IsReusable
property defines if one handler object can be pooled and shared on
different requests. If you set it to true be sure that the
ProcessRequest method is thread safe. Than we will implement the
ProcessRequest methods as follows:
using System;
using System.Web;
using System.Collections.Generic;
using System.Runtime.Serialization.Json;
public class GetStreetsByPostCode : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
List<string> streets = new List<string>();
int postCode;
string postCodeParameter =
context.Request.QueryString["code"];
if (!String.IsNullOrEmpty(postCodeParameter) &&
int.TryParse(postCodeParameter, out postCode))
{
AddressService service = new AddressService();
streets =
service.GetAvailableStreetsByPostCode(postCode);
}
DataContractJsonSerializer serializer = new
DataContractJsonSerializer(typeof(List<string>));
serializer.WriteObject(context.Response.OutputStream,
streets);
context.Response.ContentType = "application/json";
}
public bool IsReusable
{
get
{
return false;
}
}
}
As you see we are using DataContractJsonSerializer object to
serialize data in JSON format. The JSON format is native data
representation format for the JavaScript language. Also we set the
content type http header to "application/json" which is the JSON
document mime type. The AddressService is just a class used to get
data. This is all we need from server side. For client side we will
use jQuery library. Based on a selected post code we will populate
a dropdown with available streets for this post code. The script
bellow will make an ajax request to our generic handler, parse the
JSON data and fill in the dropdown values.
$(function() {
$("#DropDownPost").change(function() {
LoadAddress();
});
});
function LoadAddress() {
var selectedPostCode = $("#DropDownPostCode
option:selected").text();
if (selectedPostCode && selectedPostCode != "0") {
$.post("/GetStreetsByPostCode.ashx?code=" +
selectedPostCode,
function(result) {
var streets = eval("(" + result + ")");
ClearStreetsDropDown();
PopulateStreetsDropDown(streets);});
} else {
ClearStreetsDropDown();
}
}
function ClearStreetsDropDown() {
$('#DropDownStreet option').each(function(i, option) {
$(option).remove(); });
}
function PopulateStreetsDropDown(streets) {
$('#DropDownStreet').append(
$('<option
selected="selected"></option>').val("").html("")
);
$.each(streets, function(val, text) {
$('#DropDownStreet').append(
$('<option></option>').val(text).html(text)
);
});
}
Comments
Trackback on 5/6/2010 3:22:45 AM - CST
pkuzvcey - Google Search