與往常一樣通過定義視圖模型開始:
public class MyViewModel
{
[Required]
[DisplayName("Select a state:")]
public string SelectedState { get; set; }
public IEnumerable<SelectListItem> States { get; set; }
[Required]
[DisplayName("Select a district:")]
public string SelectedDistrict { get; set; }
public IEnumerable<SelectListItem> Districts { get; set; }
}
然後控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
// TODO: load the states initially
States = new[] { "A", "B", "C" }.Select(x => new SelectListItem
{
Value = x,
Text = x
}),
// Initially we don't have districts
Districts = Enumerable.Empty<SelectListItem>()
};
return View(model);
}
public ActionResult Districts(string state)
{
// TODO: given a state select its districts
var districts = Enumerable
.Range(1, 4)
.Select(x => string.Format("district {0} of state {1}", x, state));
return Json(districts, JsonRequestBehavior.AllowGet);
}
}
然後一個觀點:
@model MyViewModel
<div>
@Html.LabelFor(x => x.SelectedState)
@Html.DropDownListFor(
x => x.SelectedState,
Model.States,
"-- State --",
new {
id = "states",
data_url = Url.Action("districts")
}
)
</div>
<div>
@Html.LabelFor(x => x.SelectedDistrict)
@Html.DropDownListFor(
x => x.SelectedDistrict,
Model.Districts,
"-- District --",
new { id = "districts" }
)
</div>
最後一些JavaScript級聯的States
下拉:
$(function() {
$('#states').change(function() {
var url = $(this).data('url');
var selectedState = $(this).val();
$.get(url, { state: selectedState }, function (districts) {
var districtsDdl = $('#districts');
districtsDdl.empty();
$.each(districts, function (index, district) {
districtsDdl.append(
$('<option/>', {
value: district,
text: district
})
);
});
});
});
});
+1這樣的,儘管問題的質量差了詳細的解答。 –