在Asp.Net中使用JQuery绑定DropDownlists

我有3个国家,州和地铁下拉列表。 我想当用户分离国家然后状态下拉列表填充Jquery时,选择Sate然后Metro下拉列表填充(如ajax的级联下拉列表)。这个过程我想用JQuery。

我将在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); } 

在视图中,您有三个DropDownLists,一个绑定到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(''); }); }, error: function() { alert('Failed to retrieve states.'); } }); }); 

Metros下拉列表将以类似方式填充,将国家和州选择传递给服务器并返回带有一系列都市区域的JSON对象。

我省略了存储库实现的细节,只是以某种方式用服务器上的结果变量填充状态/都市区域的集合。 我还假设State类有两个属性 – Abbr(例如’CA’)和Name(例如California)。

我希望它能以任何方式帮助您,或者至少指导您以某种方式解决问题。