首页 > 解决方案 > 在 ASP.NET MVC 5 的布局中创建 HTML 下拉列表

问题描述

我有一个仪表板,sidenav 在 layout.cshtml 中。我有一个模式,其中包含一个在主页/索引中工作的下拉列表。但是,在不同的页面上,模式不会触发。然后我发现,模式需要在布局中,以便可以从任何页面触发,因为 sidenav 中的链接。

但是,当我将模式移动到 layout.cshtml 时,出现错误

Line 186: @Html.DropDownList("DomainDropDownList", ViewBag.domainSelectionList as SelectList, new { @class = "select" })

[InvalidOperationException: There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'DomainDropDownList'.]

然后我意识到这是因为没有 ViewData,因为它在 layout.cshtml 中。

我查了一下,发现我可以使用 ViewComponents,但那是在 Core 中,我没有使用 Core。

有没有人对我如何使用以下方法在 layout.cshtml 中获取下拉列表有任何建议:

SelectList DomainDropDownList = new SelectList(DomainManagement.ListIsDomainAlive(), "id", "domainName");
ViewBag.domainSelectionList = DomainDropDownList;

谢谢

标签: c#.netasp.net-mvc

解决方案


你应该改变

@Html.DropDownList("DomainDropDownList", ViewBag.domainSelectionList as SelectList, new { @class = "select" })

@Html.DropDownList("domainSelectionList", ViewBag.domainSelectionList as SelectList, new { @class = "select" })

因为ViewBag名字domainSelectionList不是DomainDropDownList


推荐阅读