我正在尝试使我的代码更具可读性。这是一个 MVC 项目,我正在使用硬编码
ViewBag.Origin = new List<SelectListItem>
{
new SelectListItem { Text = "Born", Value = "Born"},
new SelectListItem { Text = "Donated", Value = "Donated"},
new SelectListItem { Text = "Bought", Value = "Bought"}
};
很多时间在应用程序中,所以我决定将它移到存储库类中。
public class Repository
{
public List<SelectListItem> GetOriginList()
{
List<SelectListItem> originItems = new List<SelectListItem>
{
new SelectListItem { Text = "Born", Value = "Born"},
new SelectListItem { Text = "Donated", Value = "Donated"},
new SelectListItem { Text = "Bought", Value = "Bought"}
};
return originItems;
}
然后尝试访问它。
public class CowController : Controller
{
Repository repository = new Repository();
ActionResult Create() {
ViewBag.origin = repository.GetOriginList();
return View();
}
}
我的观点
@Html.DropDownList("Origin", "Select Origin")
但它查看我运行时错误。
An exception of type 'System.InvalidOperationException' occurred in System.Web.Mvc.dll but was not handled in user code
Additional information: The ViewData item that has the key 'Origin' is of type 'System.Collections.Generic.List`1[[System.Web.WebPages.Html.SelectListItem, System.Web.WebPages, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]' but must be of type 'IEnumerable<SelectListItem>'.
仅对动作进行硬编码时工作正常。我忘记了任何类型转换吗?