8

I have 3 dropdownlists for Country,State and Metro. I want to when user seclect Country then State dropdownlist fill Jquery and when select Sate then Metro dropdownlist fill(like cascading dropdownlist of ajax).These process i want to do with JQuery.

1 Answer 1

10

I am going to describe it in ASP.NET MVC, but the same can be achieved if you either write an ASP.NET web service or just put a few page methods in your code behind to do the same - you'll also need a JSON serializer, either a 3rd party solution or the one in WCF.

Using MVC, first, let's have three controller actions - one to display the page, countries will be static, and two to get the states and metros respectively:

public ActionResult Index()
{
    ViewData["Countries"] = _countryRepository.GetList();
    return View();
}

public ActionResult States(string countryCode)
{
    var states = _stateRepository.GetList(countryCode);
    return Json(states);
}

public ActionResult Metros(string countryCode, string state)
{
    var metros = _metroRepository.GetList(countryCode, state);
    return Json(metros);
}

In the view, you have three DropDownLists, one is bound to the ViewData["Countries"] object, say it's named Countries, you can get the states in jQuery with an Ajax call like this:

$('#Countries').change(function() {
    var val = $(this).val();
    $states = $('#States');
    $.ajax({
        url: '<%= Url.Action('States') %>',
        dataType: 'json',
        data: { countryCode: val },
        success: function(states) {
            $.each(states, function(i, state) {
                $states.append('<option value="' + state.Abbr+ '">' + state.Name + '</option>');
            });
        },
        error: function() {
            alert('Failed to retrieve states.');
        }
    });
});

The Metros drop down would be filled analogically, passing both the country and state selection to the server and getting back a JSON object with an array of metro areas.

I left out the details of repository implementation, just fill up the result variable on the server with a collection of states/metro areas in some way. I also made an assumption that the State class would have two properties - Abbr (e.g., 'CA') and Name (e.g., California).

I hope that it helps you in any way, or at least directs you somehow towards the solution.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks very much, works for me too! did have to put a < in front of the option value....
One note, if not parsing into json and returning something like List<T>, I had to use states.d or else the properties were always undefined.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.