使用jQuery绑定DropDownlists在Asp.Net [英] Bind DropDownlists with JQuery in Asp.Net
问题描述
我有3个dropdownlists的国家,州和地铁。
我想,当用户seclect 国家和状态的DropDownList填充jQuery和当选择沙爹和地铁的DropDownList填充(如AJAX级联的DropDownList)。这些过程我想用jQuery做的。
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.
推荐答案
我要描述它在ASP.NET MVC的,但如果你要么写一个ASP.NET Web服务或只是把几个同样可以实现在code后面的页面方法做同样的 - 你还需要一个JSON序列化,无论是第三方解决方案或一个在WCF
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.
使用MVC,首先,让我们有三个控制器动作 - 一个显示页面,国家将静态的和两个分别获得国家和地铁:
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);
}
在视图中,您有三个DropDownLists,一个是绑定到计算机[国家]对象,说这是国家命名的,你可以在jQuery的状态与Ajax调用是这样的:
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.');
}
});
});
该都市圈下拉将类推填补,同时传递国家和状态选择到服务器,并取回一个JSON对象与地铁领域的数组。
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.
我离开了仓库实现的细节,只需填写在服务器上的结果变量,州/都市地区以某种方式集合。我还做了一个假设,即State类将有两个属性 - 缩写(例如,CA)和名称(例如,加利福尼亚州)
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.
这篇关于使用jQuery绑定DropDownlists在Asp.Net的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!