Header Ads

Populate dropdown Listbox using Ajax

AJAX :: Asynchronous JAvascript Xml.

AJAX is not a new technology. The parts of AJAX are HTML, XML, DOM, JavaScript, XMLHTTP. Use all of these together, that is what AJAX.

Where AJAX can be used effectively?

* Submit and get Server Response without doing Page Postback.
* Do the Asynchronous call to the server and get response from it.

Steps to implement Ajax with .Net

1. Create a XMLHTTP Object.
2. Submit the Request data to the Server.
3. Implement Http Handler to handle HTTP requests. In .Net, there is a file called .ashx
4. Send the XML Data to the Client.
5. Parse the XML Data and make use of it.

The XML Content which is sent from Server-side as follows

<StateSet>
<State>
<StateID>1</StateID>
<StateName>Tamil Nadu</StateName>
</State>
<State>
<StateID>2</StateID>
<StateName>Karnataka</StateName>
</State>
<State>
<StateID>3</StateID>
<StateName>Andhra Pradesh</StateName>
</State>
<State>
<StateID>4</StateID>
<StateName>Kerala</StateName>
</State>
</StateSet>



The following AjaxDemo is a Class, which contains two public properties RequestUrl, and objXmlHttp. If you want to learn more about Object Oriented JavaScript which is published under Javascript Section. [Click here to go]


function AjaxDemo(AjaxHandlerPath)
{
    this.RequestUrl = AjaxHandlerPath;
    this.objXmlHttp;
    this.getHttpObject = getHttpObject;
    this.getResponseXml = getResponseXml;
}


The following method getHttpObject() which returns XMLHttpObject which is used to handle HTTP Requests.


function getHttpObject()
{
    try
    {
        this.objXmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch(e)
    {
        try
        {
            this.objXmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch(e)
        {
            this.objXmlHttp = new XMLHttpRequest();
        }
    }
}


The following method getResponseXml() which gets the parameters such as the values which are required to access the server data. For example, For getting list of States, CountryID is required. So, the paramValues will be "CountryID=1".

function getResponseXml(paramValues)
{
    var XmlDataObject;
    
    this.getHttpObject();
    if(this.objXmlHttp)
    {
        this.objXmlHttp.open("POST", this.RequestUrl, false);
        this.objXmlHttp.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded; charset=UTF-8");
this.objXmlHttp.send(paramValues);

XmlDataObject = this.objXmlHttp;
    }
    return XmlDataObject;
}



The below method populateDropDown() which will be called when Country dropdown listbox gets changed.


function populateDropdown()
{
    // 1. Clear up the drop down list box.
    var ddlStateControl = document.getElementById("ddlState");
    clearControl(ddlStateControl);
    var sRequestUrl = "http://localhost:1929/StevePencil/AjaxHandler.ashx";
    var iCountryID = document.getElementById("ddlCountry").value;

    /* 2. Create the Object for AjaxDemo, pass the RequestUrl as a parameter.
          Call the method getResponseXml() to get the XmlContent Object. */
    var oAjaxDemo = new AjaxDemo(sRequestUrl);
    var XmlDataObject = oAjaxDemo.getResponseXml("CountryID=" + iCountryID);
    var XmlContent = XmlDataObject.responseXml;
    
    // 3. Parse the Xml Content and fill it up the dropdown list box.
    var XMLRS = XmlContent.documentElement.getElementsByTagName("State");
            
    var StateID, StateName;
    ddlStateControl[0] = new Option("-- Select State --", "0");
    for(i=0; i<XMLRS.length; i++)
    {
        StateID = XMLRS.item(i).getElementsByTagName("StateID").item(0).text;
        StateName = XMLRS.item(i).getElementsByTagName("StateName").item(0).text;
        ddlStateControl[i+1] = new Option(StateName, StateID);
    }
}



Now, We are going to look at the Code for Handler. In VisualStudio 2005, When you try to add the New File, the option will be Generic Hanldler, and its extension is .ashx. But in Visual Studio 2003, there is no option such as Generic Handler, but still we can create the file as .ashx
If you look at the code, you can find the difference like, Usually all the classes would inherit Page Class. But, this class AjaxHandler inherits IHttpHandler interface.

When HTTP request invokes by XMLHttp Object, directly, this ProcessRequest() method will be called, and whatever querystring values have been passed thorugh XMLHttp Object can be accessed by using context object.

In our example, CountryID is passed as a Querystring, which can be accessed as context.Request["CountryID"].

Next Important thing, Once we get the XML Content which is generated from DataSet, should be written back to the Client. Right? How to do that?

Yes, We need to write that output content into context object. So, it can be accessible by using XMLHttpObject.


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

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

public class AjaxHandler : IHttpHandler 
{    
    public void ProcessRequest (HttpContext context) 
    {
        context.Response.ContentType = "text/xml";
        if (context.Request["CountryID"] != null)
        {
            int iCountryID = Int32.Parse(context.Request["CountryID"].ToString());
            DataSet dstState = this.getStates(iCountryID);
            context.Response.Write(dstState.GetXml());
        }
    }

    private DataSet getStates(int iCountryID)
    {
        DataSet dstData = new DataSet("StateSet");

        string sCon = ConfigurationManager.AppSettings["ConnectionString"];
        SqlConnection objCon = new SqlConnection(sCon);
        SqlCommand objCmd = new SqlCommand("getStates", objCon);

        objCmd.CommandType = CommandType.StoredProcedure;
        SqlParameter param = null;

        param = new SqlParameter("@CountryID", SqlDbType.Int);
        param.Value = iCountryID;
        objCmd.Parameters.Add(param);

        SqlDataAdapter objAdapter = new SqlDataAdapter(objCmd);

        objAdapter.Fill(dstData, "State");

        return dstData;
    }
 
    public bool IsReusable
    {
        get {
            return false;
        }
    }
}



So, finally Once the content is written into the Context, that can be accessible at ClientSide. For looking at the content which is written back, we need to use objXmlHttp.responseXml property. If you look at populateDropdown() method, you can find the XmlDataObject.responseXml() method, which is used to get Xml content sent from Server-side.

No comments:



Powered by Blogger.