【发布时间】:2011-01-12 21:02:35
【问题描述】:
我想在我网站的所有页面中包含一个包含年份的下拉列表。我认为放置这个逻辑的好地方是布局页面(_layout.cshtml)。如果用户更改年份,我也想更改我的年份会话(ModelBinder)以更改。这在 ASP.NET Web 表单中很容易做到,但在 MVC 中似乎几乎不可能做到。我尝试了一个没有运气的部分视图。有人有什么想法吗?
【问题讨论】:
-
您遇到了什么特殊问题?
我想在我网站的所有页面中包含一个包含年份的下拉列表。我认为放置这个逻辑的好地方是布局页面(_layout.cshtml)。如果用户更改年份,我也想更改我的年份会话(ModelBinder)以更改。这在 ASP.NET Web 表单中很容易做到,但在 MVC 中似乎几乎不可能做到。我尝试了一个没有运气的部分视图。有人有什么想法吗?
【问题讨论】:
像往常一样,您可以从定义视图模型开始:
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) {
});
});
});
【讨论】: