web 2.0

Dynamic Select Lists with MVC and jQuery

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)

Comments

Jose Marmolejos Dominican Republic, on 1/27/2010 7:51:35 PM Said:

Jose Marmolejos

If you want you can expand your example with some of the customizations found on this plugin: http://code.google.com/p/jquery-cascade/  </shameless plug>.

And also, in the server side of things you can have a return a linq result like:

return Json(countries.Where(c => c.Id == CountryId).Select(c => new { value = c.Id, label = c.Name}))

Filtering by the id is something you are supposed to return from the service, but use your imagination and add all sorts of creative properties to filter by.

DotNetKicks.com , on 1/27/2010 8:36:13 PM Said:

trackback

Dynamic Select Lists with MVC and jQuery

You've been kicked (a good thing) - Trackback from DotNetKicks.com

drakz.com , on 1/27/2010 11:47:39 PM Said:

pingback

Pingback from drakz.com

Code Capers | Dynamic Select Lists with MVC and jQuery | Drakz Free Online Service

DotNetShoutout , on 1/28/2010 6:16:37 PM Said:

trackback

Code Capers | Dynamic Select Lists with MVC and jQuery

Thank you for submitting this cool story - Trackback from DotNetShoutout

uberVU - social comments , on 1/28/2010 9:59:23 PM Said:

trackback

Social comments and analytics for this post

This post was mentioned on Twitter by mikeceranski: blogged:  Dynamic Select Lists with MVC and jQuery http://goo.gl/fb/Yyuu #aspnet #jquery #mvc #programming

Josh Kodroff United States, on 2/1/2010 11:09:55 AM Said:

Josh Kodroff

This is much slicker than the solution I posted on StackOverflow (which might still be useful for people that can't use jQuery for political reasons): stackoverflow.com/.../1977055#1977055

Brian United States, on 2/18/2010 4:07:38 PM Said:

Brian

Crucial Tip:  Set the name attribute on the states select.  Might not post otherwise.  God, Web Forms has made me dumb.

Andrei Rinea Romania, on 3/22/2010 6:40:14 AM Said:

Andrei Rinea

You can also use Microsoft's CDN. Here's a post about how : weblogs.asp.net/.../...the-microsoft-ajax-cdn.aspx

thinkingindotnet.wordpress.com , on 3/22/2010 6:01:12 PM Said:

pingback

Pingback from thinkingindotnet.wordpress.com

Enlaces de Marzo: ASP.NET, ASP.NET MVC, AJAX, Visual Studio, Silverlight « Thinking in .NET

nitrix-reloaded.com , on 3/23/2010 11:47:09 PM Said:

pingback

Pingback from nitrix-reloaded.com

Nice Learning Resources: ASP.NET, ASP.NET MVC, AJAX, Visual Studio, Silverlight  - NitRiX Reloaded

iAwaaz-News-by-People , on 3/28/2010 1:05:58 AM Said:

trackback

Code Capers | Dynamic Select Lists with MVC and jQuery

Thank you for submitting this cool story - Trackback from iAwaaz-News-by-People

weblogs.asp.net , on 3/29/2010 5:01:54 AM Said:

pingback

Pingback from weblogs.asp.net

Daily tech links for .net and related technologies - Mar 29-31, 2010 - Sanjeev Agarwal

Блог Краковецкого Александра , on 3/30/2010 9:15:48 AM Said:

trackback

Полезные ссылки 2

Свежая подборка ссылок (часть ссылок взята из блога Скотта Гатри ). Microsoft Почему я люблю Microsoft

Code Capers , on 4/19/2010 12:35:49 AM Said:

trackback

Advice for Aspiring ASP.NET Web Developers

Advice for Aspiring ASP.NET Web Developers

shinguyen.net , on 5/3/2010 10:06:10 PM Said:

pingback

Pingback from shinguyen.net

March 21st Links: ASP.NET, ASP.NET MVC, AJAX, Visual Studio, Silverlight | OOP – Object Oriented Programing

227.jordanbrandallamerican.com , on 5/20/2010 1:19:23 PM Said:

pingback

Pingback from 227.jordanbrandallamerican.com

Rio5 Wholesale Aftermarket, Sephia Discount Body Parts Sorento Kia Rio5

Comments are closed