asp.net-mvc MVC 3 布局页面、Razor 模板和下拉列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4674033/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MVC 3 Layout Page, Razor Template, and DropdownList
提问by Sam Stange
I want to include a drop down list of years across all the pages in my website. I assumed a good place to put this logic was in the layout page (_layout.cshtml). If a user changes the year I want to change my year session (ModelBinder) to change as well. This was so easy to do with ASP.NET web forms, but seems near impossible to do in MVC. I tried a partial view with no luck. Anybody have any ideas?
我想在我网站的所有页面中包含一个年份的下拉列表。我认为放置此逻辑的好地方是在布局页面 (_layout.cshtml) 中。如果用户更改年份,我也想更改我的年份会话 (ModelBinder) 以进行更改。使用 ASP.NET Web 表单很容易做到这一点,但在 MVC 中似乎几乎不可能做到。我尝试了部分视图,但没有运气。有人有任何想法吗?
回答by Darin Dimitrov
As usual you could start by defining a view model:
像往常一样,您可以从定义视图模型开始:
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");
}
}
}
Then a controller:
然后是一个控制器:
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();
}
}
and a corresponding view for the index action:
以及索引操作的相应视图:
@model SomeAppName.Models.YearsViewModel
@{
Layout = null;
}
@Html.DropDownListFor(x => x.Year, Model.Years)
And finally inside your _Layout.cshtml
you could use this controller:
最后在你的内部_Layout.cshtml
你可以使用这个控制器:
<div id="selectyear">@Html.Action("index", "years")</div>
and attach a corresponding script which would send an AJAX request when the value changes:
并附上相应的脚本,该脚本将在值更改时发送 AJAX 请求:
$(function () {
$('#selectyear select').change(function () {
$.post('@Url.Action("index", "years")', { year: $(this).val() }, function (result) {
});
});
});