如何将列表项发送到多个页面的部分视图中的下拉列表
how to send list item to dropdown in a partial view on multiple pages
我在多个页面的下拉列表中显示数据时遇到了一些问题。
场景:我有 5 个页面在所有这些 pages.In 这个局部视图上具有相同的局部视图,有两个下拉列表。
现在,有两个控制器,一个是家庭控制器,另一个是 Post 控制器。
Home controller 的 index action 方法是:
public ActionResult Index()
{
List<City> allCity = new List<city>();
using (ApplicationDbContext dc = new ApplicationDbContext())
{
allCity = dc.Cities.OrderBy(a => a.CityName).ToList();
}
ViewBag.CityId = new SelectList(allCity, "Id", "CityName");
return View();
}
现在,在部分视图中,我将数据发送到下拉列表,如下所示:
@model App.Models.City
<div class="dropdown">
@Html.DropDownList("Id", ViewBag.CityId as SelectList, new { @class = "short_dropdown" })
并将此部分视图呈现给所有页面,如下所示:
<section class="container">
@Html.Partial("_CommentBox")
现在,如果我看到家庭控制器的 index.cshtml 页面,则下拉列表中的值已正确填充。
但是,如果我转到 Post 控制器的索引页,则错误是:**
There is no ViewData item of type 'IEnumerable' that has the key 'Id'.
System.InvalidOperationException: There is no ViewData item of type 'IEnumerable' that has the key 'Id'.
如何解决这个问题。我是否必须将数据与局部视图一起发送?如果是,那么我在一个局部视图中有两个下拉菜单,然后如何为这两个下拉菜单发送数据。
在您的 Post 控制器中进行与您在 Home 控制器中相同的操作以填充 ViewBag.CityId
。并且为了避免代码重复,您可以将其移动到一个可以重复使用的单独方法中:
public static List<City> GetCities()
{
using (ApplicationDbContext dc = new ApplicationDbContext())
{
return dc.Cities.OrderBy(a => a.CityName).ToList();
}
}
然后在两个控制器中填充ViewBag.CityId
:
ViewBag.CityId = new SelectList(SomeDomain.GetCities(), "Id", "CityName");
我在多个页面的下拉列表中显示数据时遇到了一些问题。 场景:我有 5 个页面在所有这些 pages.In 这个局部视图上具有相同的局部视图,有两个下拉列表。 现在,有两个控制器,一个是家庭控制器,另一个是 Post 控制器。 Home controller 的 index action 方法是:
public ActionResult Index()
{
List<City> allCity = new List<city>();
using (ApplicationDbContext dc = new ApplicationDbContext())
{
allCity = dc.Cities.OrderBy(a => a.CityName).ToList();
}
ViewBag.CityId = new SelectList(allCity, "Id", "CityName");
return View();
}
现在,在部分视图中,我将数据发送到下拉列表,如下所示:
@model App.Models.City
<div class="dropdown">
@Html.DropDownList("Id", ViewBag.CityId as SelectList, new { @class = "short_dropdown" })
并将此部分视图呈现给所有页面,如下所示:
<section class="container">
@Html.Partial("_CommentBox")
现在,如果我看到家庭控制器的 index.cshtml 页面,则下拉列表中的值已正确填充。 但是,如果我转到 Post 控制器的索引页,则错误是:**
There is no ViewData item of type 'IEnumerable' that has the key 'Id'. System.InvalidOperationException: There is no ViewData item of type 'IEnumerable' that has the key 'Id'.
如何解决这个问题。我是否必须将数据与局部视图一起发送?如果是,那么我在一个局部视图中有两个下拉菜单,然后如何为这两个下拉菜单发送数据。
在您的 Post 控制器中进行与您在 Home 控制器中相同的操作以填充 ViewBag.CityId
。并且为了避免代码重复,您可以将其移动到一个可以重复使用的单独方法中:
public static List<City> GetCities()
{
using (ApplicationDbContext dc = new ApplicationDbContext())
{
return dc.Cities.OrderBy(a => a.CityName).ToList();
}
}
然后在两个控制器中填充ViewBag.CityId
:
ViewBag.CityId = new SelectList(SomeDomain.GetCities(), "Id", "CityName");