Cascading dropdownlist in ASP.NET MVC with jQuery

One of the very common task when you are working in web is cascading dropdowns. In asp.net web forms it was commonly done by AutoPostBack property of Dropdown List controller. The problem page does full post back. A better approach to do this is ASP.Net MVC with jQuery.

This article will show you how to work with cascading dropdown list with ASP.Net MVC and jQuery. We have two dropdown lists one Country and State and on change of Country dropdown list we will populate state dropdown list.

Cascading dropdownlist in ASP.NET MVC with jQuery

Cascading dropdownlist in ASP.NET MVC with jQuery

We have two model (Country, State) one controller and cshtml page.

Let’s start with Country model

namespace sample1.Models
{
    public class Country
    {
        public string CountryCode { get; set; }
        public string CountryName { get; set; }

        public static List<Country> GetCountries()
        {
            return new List<Country>
            {
                new Country {
                    CountryCode = "In",
                    CountryName = "India"
                },
                new Country{
                    CountryCode = "US",
                    CountryName = "United-States"
                }
            }.ToList();
        }
    }
}

Now create state model

namespace sample1.Models
{
    public class State
    {
        public string CountryCode { get; set; }
        public int StateID { get; set; }
        public string StateName { get; set; }

        public static List<State> GetStates()
        {
            return new List<State>
            {
                new State
                    {
                        CountryCode = "In",
                        StateID=1,
                        StateName = "Maharashtra"
                    },
                new State
                    {
                        CountryCode = "In",
                        StateID=2,
                        StateName = "Andhra Pradesh"
                    },
                new State
                    {
                        CountryCode = "In",
                        StateID=3,
                        StateName = "Tamil Nadu"
                    },
                new State
                    {
                        CountryCode = "In",
                        StateID=4,
                        StateName = "Goa"
                    },
                new State
                    {
                        CountryCode = "US",
                        StateID=11,
                        StateName = "New-York"
                    },
                new State
                    {
                        CountryCode = "US",
                        StateID=12,
                        StateName = "California"
                    },
                new State
                    {
                        CountryCode = "US",
                        StateID=13,
                        StateName = "Washington"
                    },
                new State
                    {
                        CountryCode = "US",
                        StateID=14,
                        StateName = "Vermont"
                    }
            }.ToList();
        }
    }
}

Create controller and add two methods to get list of Country and State where Country List will return list of countries this method will call on page load first time and Stateliest will accept a parameter country code and returns state of respective country code.

public JsonResult CountryList()
{
    List<Country> countries = Country.GetCountries();
    return Json(countries, JsonRequestBehavior.AllowGet);
}

public JsonResult StateList(string CountryCode)
{
    List<State> states = State.GetStates().Where(x => x.CountryCode == CountryCode).ToList();
    return Json(states, JsonRequestBehavior.AllowGet);
}

Now on cshtml page add two dropdown list and a script at document load

<table>
    <tr>
        <td>Countries</td>
        <td>States</td>
    </tr>
    <tr>
        <td><select id="Countries" name="Countries"></select></td>
        <td><select id="States" name="States"></select></td>
    </tr>
</table>

On document ready we will do two things first load country dropdown list for that we are using getJSON method to get list of country and populate it in country dropdown list.
In second part will hook the country dropdown change event to a function which get the country code and populate state dropdown list. This is most important part.

    $(function () {
        $.getJSON("/Cascade/CountryList", null, function (data) {
            var items = "<option>Select Country</option>";
            $.each(data, function (i, item) {
                items += "<option value=" + item.CountryCode + ">" + item.CountryName + "</option>";
            });
            $("#Countries").html(items);
        });

        $("#Countries").change(function () {
            var Param = { CountryCode: $("#Countries > option:selected").attr("value") };
            $.getJSON("/Cascade/StateList/", Param, function (data) {
                var items = "<option>Select State</option>";
                $.each(data, function (i, state) {
                    items += "<option value=" + state.StateID + ">" + state.StateName + "</option>";
                });
                $("#States").html(items);
            });
        });
    });

and that’s ….

Advertisements
This entry was posted in jQuery, MVC and tagged , . Bookmark the permalink.

One Response to Cascading dropdownlist in ASP.NET MVC with jQuery

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