如何解决将下拉列表与模型绑定会引发错误
我正在尝试使用实体框架将下拉列表绑定到模型,但出现一条错误消息:
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 举报,一经查实,本站将立刻删除。