Sam*_*nge 33 asp.net-mvc asp.net-mvc-3
我想在我的网站的所有页面中包含一个下拉列表.我假设一个好的地方把这个逻辑放在布局页面(_layout.cshtml)中.如果用户更改年份,我想更改我的年会(ModelBinder)也要更改.这对于ASP.NET Web表单来说非常容易,但在MVC中几乎不可能做到.我尝试了一个没有运气的局部视图.有人有什么想法吗?
Dar*_*rov 88
像往常一样,您可以从定义视图模型开始:
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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后一个控制器:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
以及索引操作的相应视图:
@model SomeAppName.Models.YearsViewModel
@{
Layout = null;
}
@Html.DropDownListFor(x => x.Year, Model.Years)
Run Code Online (Sandbox Code Playgroud)
最后_Layout.cshtml你可以使用这个控制器:
<div id="selectyear">@Html.Action("index", "years")</div>
Run Code Online (Sandbox Code Playgroud)
并附加一个相应的脚本,当值发生变化时会发送一个AJAX请求:
$(function () {
$('#selectyear select').change(function () {
$.post('@Url.Action("index", "years")', { year: $(this).val() }, function (result) {
});
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
61157 次 |
| 最近记录: |