【问题标题】:MVC 3 Layout Page, Razor Template, and DropdownListMVC 3 布局页面、Razor 模板和 DropdownList
【发布时间】:2011-01-12 21:02:35
【问题描述】:

我想在我网站的所有页面中包含一个包含年份的下拉列表。我认为放置这个逻辑的好地方是布局页面(_layout.cshtml)。如果用户更改年份,我也想更改我的年份会话(ModelBinder)以更改。这在 ASP.NET Web 表单中很容易做到,但在 MVC 中似乎几乎不可能做到。我尝试了一个没有运气的部分视图。有人有什么想法吗?

【问题讨论】:

  • 您遇到了什么特殊问题?

标签: asp.net-mvc asp.net-mvc-3


【解决方案1】:

像往常一样,您可以从定义视图模型开始:

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) {

        });
    });
});

【讨论】:

  • 太棒了。将其改编为完全没有问题的国家选择器。感谢负载。
  • 这对于提供清晰的 ASP.NET MVC 实现非常有帮助。除了如何在页面上放置下拉菜单,这里还有很多东西要学习,谢谢。
  • @DarinDimitrov 嗨。感谢这项伟大的工作。但有人怀疑我将如何使用 ViewBag 来做到这一点。我需要使用 viewbag r 会话绑定布局页面中的下拉菜单。因为如果我在我的布局页面中指定了“@model SomeAppName.Models.YearsViewModel”,则意味着我无法从我的内容页面传递任何模型来查看返回视图(“home”,Detail),因为这里的布局除了 yearviewmodel。所以它会抛出错误。
猜你喜欢
  • 2017-01-28
  • 1970-01-01
  • 2021-10-25
  • 1970-01-01
  • 2011-08-17
  • 2019-09-21
  • 1970-01-01
  • 2020-12-14
  • 1970-01-01
相关资源
最近更新 更多