我将在ASP.NET MVC中描述它,但是如果您编写一个ASP.NET Web服务或只是在代码中放置一些页面方法来完成相同的工作,也可以实现相同的效果-您还需要一个JSON序列化程序,第三方解决方案或WCF中的一个。
使用MVC,首先,让我们有三个控制器操作-一个显示页面,国家是静态的,两个分别获取国家和地铁:
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);
}
在视图中,您有三个下拉列表,一个绑定到viewdata[“countries”]对象,比如说它是命名的countries,您可以通过这样的Ajax调用在jquery中获取状态:
$('#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.');
}
});
});
Metros下拉列表将以类似的方式填充,将国家和状态选择传递给服务器,并使用Metro区域数组返回JSON对象。
我遗漏了存储库实现的细节,只是在服务器上以某种方式用状态/高速区域的集合填充结果变量。我还假设州类有两个属性——abbr(如“ca”)和name(如加利福尼亚)。
我希望它能以任何方式帮助你,或者至少能指导你找到解决方案。