在Asp.net MVC 中实现级联下拉列表是一件很容易的事,用Jquery配合@Html.DropDownList可以很方便,但是现在有了knockoutjs
用knockoutjs实现级联会更简洁和优雅,不必每次选择之后还要遍历。
例如,要做一个选择省份,然后根据选择的省份显示另一个市级的下拉列表,要实现这个功能,在Asp.net MVC 中Controller代码如下:
public class HomeController : Controller { public ActionResult Index() { ViewBag.Country = new SelectList(Country.GetCountryList(), "Code", "Name"); return View(); } public ActionResult GetStates(string id = "") { var stateList = State.GetStates() .Where(s => s.CountryCode.ToLower() == id.ToLower()); return this.Json(stateList, JsonRequestBehavior.AllowGet); } } public class State { public string CountryCode { get; set; } public int StateId { get; set; } public string StateName { get; set; } }
在客户端index.cshtml中的代码如下:
<p> <b>选择省份 :</b> @Html.DropDownList("ddlCountry", ViewBag.Country as SelectList, "...请选择...", new { onchange = "FetchStates();" }) </p> <p data-bind="visible: states().length > 0"> <b>选择市级 :</b> <select data-bind="options: states, optionsText: 'StateName', optionsValue: 'StateId', optionsCaption: '...请选择...'"></select> </p>
使用knockoutjs绑定的JavaScript代码如下:
function CascadingDDLViewModel() { this.states = ko.observableArray([]); } var objVM = new CascadingDDLViewModel(); ko.applyBindings(objVM);
从上面的代码中可以看到市级数据绑定到states,当states的值改变时自动更新select列表
当选择省份的时候需要去服务端获取数据,代码如下:
function FetchStates() { var countryCode = $("#ddlCountry").val(); $.getJSON("/Home/GetStates/" + countryCode, null, function (data) { objVM.states(data); }); }
获取数据之后,不需要遍历加载select,只需要给states赋值,select会自动刷新。