开发者

Bind DropDownlists with JQuery in Asp.Net

I have 3 dropdownlists for Country,State and Metro. I wa开发者_Go百科nt 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜