Thursday, November 6, 2008

Using PageMethods & JSON to provide auto population

One of the problem that I have to solve in my recent project was to provide a look up for city, county, state based on a zip code. There are multiple ways of doing this - but in this exercise, I want to demonstrate using javascript (client-side) to call PageMethods (server-side) and then populate my fields.

1. Set EnablePageMethod to true in your script manager



2. Create your PageMethod


When the PageMethod returns its value, it will get serialized into JSON object. In my example above, I an returning a IEnumerable - but you can return any object, as long as it is serializable.

3. Create your javascript to call the PageMethod and callback handler
When you call a PageMethod, the result from the PageMethod is directly transfered into your callback function. In my example below - it is transfered into "result". You can also specify success path callback and failure path callback if you want.
function GetZip(zipBox) {
var zip = zipBox.value;
if (zip.toString().length >= 5) {
var x = PageMethods.GetCityCountyState(zip, GetCityCountyState_Callback);
}
function GetCityCountyState_Callback(result) {
cityDDL = document.getElementById("cityDDL");
cityDDL.options.length = 0;
var oldValue = "";
for (i = 0; i < result.length; i++) {
if (oldValue != result[i][1]) {
var newValue = result[i][1];
var newText = result[i][2];
var objOption = new Option(newText, newValue);
cityDDL.options.add(objOption);
oldValue = newValue;
}
}

countyDDL = document.getElementById("countyDDL");
countyDDL.options.length = 0;
oldValue = "";
for (i = 0; i < result.length; i++) {
if (oldValue != result[i][3]) {
var newValue = result[i][3];
var newText = result[i][4];
var objOption = new Option(newText, newValue);
countyDDL.options.add(objOption);
oldValue = newValue;
}
}

stateDDL = document.getElementById("stateDDL");
stateDDL.options.length = 0;
oldValue = "";
for (i = 0; i < result.length; i++) {
if (oldValue != result[i][5]) {
var newValue = result[i][5];
var newText = result[i][6];
var objOption = new Option(newText, newValue);
stateDDL.options.add(objOption);
oldValue = newValue;
}
}
}

So in my javascript above, I basically waiting until the textbox for zipcode is filled with 5 numbers before calling the PageMethod. Once I get the result back as JSON object, my callback function will take over and populate my drop down list for City, County, and State.

Additional readings:
1. ASP.net: Exposing WebServices To AJAX Tutorial
2. AJAX PageMethods, JSON Serialization, and a little bit of LINQ databinding
3. Passing JSON param

Related Posts:
ASP.NET MVC, AJAX, jQuery

1 comment:

Dan said...

Awesome example. Thanks!!!!