Simple Cascading Drop Down List using ASP.Net AJAX


Here is a step by step tutorial to create a simple cascading drop down list,

1) Add a new asp.bet (aspx) page and 2 drop down controls into it.

<asp:DropDownList ID="One" runat="server">

</asp:DropDownList><br />

<asp:DropDownList ID="Two" runat="server">

</asp:DropDownList>

2) Add some server side code to populate the first drop down, depending on selection on first drop down we will populate the second one. (well thats the idea 🙂

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

            //Populate "One"

            One.Items.Add(new ListItem("BMW", "BMW"));

            One.Items.Add(new ListItem("Audi", "Audi"));

            One.Items.Add(new ListItem("Honda", "Honda"));

            One.Items.Add(new ListItem("Pick One", ""));

            One.Items[3].Selected = true;

            Two.Items.Add(new ListItem("Pick One", ""));

            //add attribute for "One"

            One.Attributes.Add("onchange", "return getModels();");

        }

    }

3) ok, at this point, its worth running your project and see whether controls display propery with the first list showing makes of the cars and second one showing the default item.

4) Switch back to aspx code, and add a scriptmanager control to it (this is the heart of asp.net ajax… read more here.. Make sure that EnablePageMethods is set to true. This will enable us to call server side page methods from Javascript.

<asp:ScriptManager ID="sm" runat="server" EnablePageMethods="true" >

</asp:ScriptManager>

5) Now we are ready to write some javascript code, you might have noticed (and you got a script error possibly when you ran your project the first time) that we have added “onchange” event attribute to our first drop down list. Now we will write some javascript code to handle it. What we will do is to call the server side method to get the second drop down’s values and populate the control with it.

When we call server side method, we use PageMethods. format. Here is how our server side method will look like,

[System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]

public static string GetModels(string key)

{

    if (key == "BMW")

    {

        return ("330 i|330 xi|530 i|530 xi|750 i|X5|X3");

    }

    if (key == "Audi")

    {

        return ("A4|A4 Turbo|A6 Quattro|A8 Q");

    }

    if (key == "Honda")

    {

        return ("Civic EX|Accord EX-L|Accord EX-LV6|Pilot EX");

    }

    return ("");

    

}

Simple isn’t it? Notice the attributes set on the method. These attributes will enable it to be accessible from the Javascript side. So back to Javascript now…below given code shows it all…

<script language="javascript" type="text/javascript" >

//This is the mehod called from first drop downs "onchange" event

function getModels()

{

    var makelist = document.getElementById("One");

    // get selected car make from dropdown list

    var key = makelist.options[makelist.selectedIndex].value;

    // call the method on the server and wait till the code

    // has completed its execution.

    PageMethods.GetModels(key,OnGetModelsComplete);

}

function OnGetModelsComplete(result)

{  

    //you get the related models of car here!

    //use it to populate the drop down

    PopulateModels(result);

}

function PopulateModels(result)

{

    var models = document.getElementById("Two");

    for (var count=models.options.length-1;count > -1; count–)

    {    

        models.options[count] = null;

    }

    var items = result.split(‘|’);

    

    var idValue;

    var textValue;

    var optionItem;

    for(i = 0; i < items.length;i++)

    {

        textValue = items[i];

        idValue = items[i];

        optionItem = new Option( textValue, idValue,  false, false);

        models.options[i] = optionItem;

    }

}

</script>

The out-of-band call on PageMethods…. takes the first parameter as the input to the function and the second parameter the callback function name. This function will be calledback when the response gets back from the server…and rest is
all simple as taking the result and doing what ever you want with it..in this case build second drop down list option values…

Cheers!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s