像往常一样,您可以从定义视图模型开始:
public class YearsViewModel
{
public string Year { get; set; }
public IEnumerable<SelectListItem> Years
{
get
{
return new SelectList(
Enumerable.Range(1900, 112)
.OrderByDescending(year => year)
.Select(year => new SelectListItem
{
Value = year.ToString(),
Text = year.ToString()
}
), "Value", "Text");
}
}
}
然后是控制器:
public class YearsController : Controller
{
public ActionResult Index()
{
return View(new YearsViewModel());
}
[HttpPost]
public ActionResult Index(int year)
{
// TODO: do something with the selected year
return new EmptyResult();
}
}
以及索引操作的相应视图:
@model SomeAppName.Models.YearsViewModel
@{
Layout = null;
}
@Html.DropDownListFor(x => x.Year, Model.Years)
最后在你的里面_Layout.cshtml
你可以使用这个控制器:
<div id="selectyear">@Html.Action("index", "years")</div>
并附加一个相应的脚本,该脚本将在值更改时发送 AJAX 请求:
$(function () {
$('#selectyear select').change(function () {
$.post('@Url.Action("index", "years")', { year: $(this).val() }, function (result) {
});
});
});