问题描述
我正在尝试使用实体框架将下拉列表绑定到模型,但出现一条错误消息:
system.invalidOperationException: 'There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'OfficeName'.'
下面是我的Model类:
public partial class bookAssignment_new
{
public int ID { get; set; }
public Nullable<int> Book { get; set; }
public Nullable<int> OfficeID { get; set; }
public string Office { get; set; }
public IEnumerable<SelectListItem> OfficeName { get; set; }
}
下面是我的控制器:
public ActionResult Index()
{
var model = new bookAssignment_new();
using (BookAssignmentEntities db = new BookAssignmentEntities())
{
var dbData = db.OfficeNames.ToList();
model.OfficeName = GetSelectListItems(dbData);
}
return View();
}
private IEnumerable<SelectListItem> GetSelectListItems(IEnumerable<OfficeName> elements)
{
var selectList = new List<SelectListItem>();
foreach (var element in elements)
{
selectList.Add(new SelectListItem
{
Value = element.OfficeID.ToString(),Text = element.Office.ToString()
});
}
return selectList;
}
我可以看到正确的数据由GetSelectListItems()返回。
我的视图包含以下代码:
<div class="form-group">
@Html.DropDownList("OfficeName",Model.OfficeName)
</div>
我在视图中遇到了错误。我的OfficeName表如下:
下面是错误的屏幕截图:
任何帮助将不胜感激。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)