ninja star Dynamic Select Lists with MVC and jQuery

by Michael Ceranski, posted on January 27 2010

Update 1/28/2010: This article is Scott Guthrie approved (Corporate Vice President in the Microsoft Developer Division).

Scott Gu Article RT


There are occasions when you are developing a form and you need to have a drop down list that dynamically populates based on the value of another control. The classic example is a contact form that dynamically populates the states and provinces list when a country is selected. For example, when I select "United States" I want the child drop down to have entries like New York, Alabama, Texas and etcetera. When I select "Canada" I would expect to see provinces like Nova Scotia and Ontario. Fortunately, this functionality is very easy to build using ASP.NET MVC and jQuery. Best of all, we can do this without any postbacks using the jQuery Ajax functions.

To get started make sure you have a reference to the jQuery library, preferably in the HEAD section of your html. For the purposes of this example I am using jQuery version 1.4. You can either download jQuery locally or reference it directly from Google:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type="text/javascript"></script>

OR

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type="text/javascript"></script>

Now, that our jQuery reference is set we can build some HTML for our View page. The "countries" dropdown is already pre-populated but notice that the states combo is empty.

<table>
    <tr>
        <th>Country:</th>
        <td>
            <select id="countries">
                <option>-- Select a Country -- </option>
                <option value="1">United States</option>
                <option value="2">Canada</option>
            </select>
        </td>
    </tr><tr>
        <th>State:</th>
        <td>
            <select id="states">
            </select>
        </td>
    </tr>
</table>

Moving on, we will build the controller method which will get the states or provinces for a specified country.

public JsonResult GetStates(int countryID)
{
    var list = new object[] { };

    switch (countryID)
    {
        case 1:
            list = new object[] {
                new { value = 1, name = "Alabama" },
                new { value = 2, name = "Alaska" },
                new { value = 3, name = "California" }
            };
            break;
        case 2:
            list = new object[] {
                new { value = 1, name = "Ontario" },
                new { value = 2, name = "Quebec" },
                new { value = 3, name = "Nova Scotia" }
        };
        break;
    };

    return Json(list);
}

This code is static and obviously geared for a demo but you could just as easily loaded these object arrays from a database table. Please take notice of the method signature. We have a single parameter named countryID which determines what data should be returned. Also notice the return type is JsonResult. This means the object array will be serialized as JSON (JavaScript Object Notation) which can easily be consumed by jQuery. Now that the controller code is completed we can write the jQuery code.

<script type="text/javascript">
    $(document).ready(function() {    
        $("#countries").change(function() {     
            $.post("/Home/GetStates/", { countryID: $(this).val() }, function(data) {
                populateDropdown($("#states"), data);
            });
        });
    });

    function populateDropdown(select, data) {
        select.html('');
        $.each(data, function(id, option) {
            select.append($('<option></option>').val(option.value).html(option.name));
        });       
    }
</script>

Here is a breakdown of the jQuery code. First, we wire an event to the country drop down list. When a country is selected we make an asynchronous call to the GetStates method in the Home controller. The selected item in the country drop down is passed in as a variable to the method: { countryID: $(this).val() }. When the data is returned from the GetStates method we pass it off to the populateDropdown function. The populateDropDown function clears the drop down (in case it previously had values for a different country) then populates the combo dynamically. This is done by creating an option item and setting the value and text.

If you want to try this code out for yourself, then download the sample project below.

DynamicDropDown.zip (37.28 kb)

blog comments powered by Disqus

About the author

MikeMichael Ceranski is a developer specializing in the .NET stack. I have spent time as a DBA, Web Developer and even a network engineer. Up til now most of my career has revolved around the .NET stack but I have recently taken an interest in microcontrollers which has forced me to get acquainted with lower level languages such as C, and C++.

View my resume

Sponsors