精慕HU
一如既往,您从一个模型开始:public class MyViewModel{
public int? Year { get; set; }
public int? Month { get; set; }
public IEnumerable<SelectListItem> Years
{
get {
return Enumerable.Range(2000, 12).Select(x => new SelectListItem
{
Value = x.ToString(),
Text = x.ToString()
});
}
}}然后一个控制器:public class HomeController : Controller{
public ActionResult Index()
{
var model = new MyViewModel();
return View(model);
}
public ActionResult Months(int year)
{
if (year == 2011)
{
return Json(
Enumerable.Range(1, 3).Select(x => new { value = x, text = x }),
JsonRequestBehavior.AllowGet
);
}
return Json(
Enumerable.Range(1, 12).Select(x => new { value = x, text = x }),
JsonRequestBehavior.AllowGet
);
}}最后一个观点:@model AppName.Models.MyViewModel@Html.DropDownListFor(
x => x.Year,
new SelectList(Model.Years, "Value", "Text"),
"-- select year --")@Html.DropDownListFor(
x => x.Month,
Enumerable.Empty<SelectListItem>(),
"-- select month --")<script type="text/javascript">
$('#Year').change(function () {
var selectedYear = $(this).val();
if (selectedYear != null && selectedYear != '') {
$.getJSON('@Url.Action("Months")', { year: selectedYear }, function (months) {
var monthsSelect = $('#Month');
monthsSelect.empty();
$.each(months, function (index, month) {
monthsSelect.append($('<option/>', {
value: month.value,
text: month.text }));
});
});
}
});</script>显然你会注意到在我的例子中我已经硬编码了所有的值。您应该通过使用当前年份,当前月份等概念来改进此逻辑,甚至可能从存储库中获取这些值等等......但出于演示的目的,这应该足以让您走上正确的轨道。