像往常一样,你可以从定义视图模型开始:
public class Yearsviewmodel
{
public string Year { get; set; }
public IEnumerable 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里面你可以使用这个控制器:
并附加相应的脚本,当值发生更改时,将发送AJAX请求:
$(function () {
$('#selectyear select').change(function () {
$.post('@Url.Action("index","years")',{ year: $(this).val() },function (result) {
});
});
});