1

I have to bind a dropdown for country and after selecting the country state should be automatically populated in second dropdown list.

I have defined Model Class in following way.

public class Country
{
    public string Code { get; set; }
    public string Name { get; set; }
}

public class State
{
    public string Code { get; set; }
    public string Name { get; set; }
    public Country CountryName { get; set; }
}

Q1. Is this the correct way to define Model Class?

After this I have a view

  @Html.DropDownListFor(Model => Model.Country,new SelectList(ViewBag.Countries,"Code","Name"))

Q2. How and where should I write code to get states of selected country. (I have a method to get States when Country Code is passed as parameter)

public List<State> GetStates(string CountryCode)
Amit Mishra
  • 431
  • 5
  • 16
  • http://stackoverflow.com/questions/14339089/populating-dropdown-with-json-result-cascading-dropdown-using-mvc3-jquery-aj – Matt Bodily Jan 02 '14 at 20:04

1 Answers1

2

Q1: Your models look correct although I would change the following:

public Country CountryName { get; set; }

to

public Country Country { get; set; }

for better readability.

Q2: One approach would be to write a controller action to return a list of states based on a country code in JSON format and call this controller action via AJAX when a country is selected.

Controller Action:

public ActionResult GetStates(string countryCode)
{
    var states = _statesService.GetStatesByCountry(countryCode)
                     .OrderBy(x => x.Name.ToUpper());

    return Json(states.Select(x => new { value = x.Code, text = x.Name }));
}

Javascript:

$("#countryDropdownId").on("change", function () {
    var countryCode = $("#countryDropdownId option:selected").val();

    $.getJSON(
        "@Url.Action("GetStates")", 
        { countryCode: countryCode },
        function (states) {
            var statesDropdown = $("#statesDropdownId");

            statesDropdown.empty();

            $.each(states, function(index, state) {
                statesDropdown.append($("<option />", {
                    value: state.value,
                    text: state.text
                }));
            });
        }
    );
});