tags:

views:

557

answers:

3

Hi, 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.

+2  A: 

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.

Pawel Krakowiak
thanks very much, works for me too!did have to put a < in front of the option value....
Michel
Oh, I didn't notice it! Thanks, I have edited my answer.
Pawel Krakowiak
A: 

hello Pawel,

Once the drop drown list is binded on client side , how can we get selected value in code behind. Do we have to save the value in hidden control or is there any other way ??? thanks

Monu
A: 

ditto above question - why wouldn't this show up in a form post when wrapped inside a form tag ?

Steve