我有一个名为 Genre 的数据库表,其中包含以下字段:
- Id(种子主键)
- 姓名(类型名称 - 浪漫、西部等...)
我有一个名为 GenreDropDownModel
的模型类,其中包含以下代码:
public class GenreDropDownModel
{
private StoryDBEntities storyDB = new StoryDBEntities();
public Dictionary<int,string> genres { get; set; }
public GenreDropDownModel()
{
genres = new Dictionary<int,string>();
foreach (var genre in storyDB.Genres)
{
genres.Add(genre.Id, genre.Name);
}
}
}
我的 Controller Write
操作声明为:
public ActionResult Write()
{
return View(new GenreDropDownModel());
}
最后,我的 View Write.cshtml 是出现以下错误的地方:
DataBinding: 'System.Collections.Generic.KeyValuePair`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0 , Culture=neutral, PublicKeyToken=b77a5c561934e089]]' 不包含名为“Id”的属性。
@model Stories.Models.GenreDropDownModel
@{
ViewBag.Title = "Write";
}
<h2>Write</h2>
@Html.DropDownListFor(model => model.genres,new SelectList(Model.genres,"Id","Name"))
最佳答案
自 Model.genres
是一本字典,你应该这样做
@Html.DropDownListFor(model => model.genres,new SelectList(Model.genres,"Key","Value"))
这是因为在枚举时, IDictionary<TKey, TValue>
产生 KeyValuePair<TKey, TValue>
的枚举.这是您需要查看的类型,以了解属性的命名方式。
关于asp.net-mvc-3 - ASP.NET MVC 3 中 DropDownListFor 的数据绑定(bind)错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8896836/