ASP.NET MVC 3中DropDownListFor的数据绑定错误?

Xai*_*oft 3 entity-framework-4 html.dropdownlistfor asp.net-mvc-3

我有一个名为Genre的数据库表,其中包含以下字段:

  • Id(种子主键)
  • 姓名(类型名称 - 浪漫,西方等...)

我有一个Model类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);
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

我的Controller Write操作声明为:

  public ActionResult Write()
  {
      return View(new GenreDropDownModel());
  }
Run Code Online (Sandbox Code Playgroud)

最后,我查看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 =中性,PublicKeyToken = b77a5c561934e089]]'不包含名称为"Id"的属性.

@model Stories.Models.GenreDropDownModel

@{
    ViewBag.Title = "Write";
}

<h2>Write</h2>

@Html.DropDownListFor(model => model.genres,new SelectList(Model.genres,"Id","Name"))
Run Code Online (Sandbox Code Playgroud)

Jon*_*Jon 7

既然Model.genres是字典,你应该这样做

@Html.DropDownListFor(model => model.genres,new SelectList(Model.genres,"Key","Value"))
Run Code Online (Sandbox Code Playgroud)

这是因为枚举时,IDictionary<TKey, TValue>会产生枚举KeyValuePair<TKey, TValue>.这是您需要查看的类型,以查看属性的命名方式.