2012-01-17 66 views
3

我有一个名为类型有以下字段的数据库表:ASP.NET MVC 3中DropDownListFor的数据绑定错误?

  • 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); 
     } 
    } 

} 

我的控制器Write行动被宣布为S:

public ActionResult Write() 
    { 
     return View(new GenreDropDownModel()); 
    } 

最后,我的观点是Write.cshtml在那里我得到以下错误:

数据绑定:“System.Collections.Generic.KeyValuePair`2 [[System.Int32,mscorlib程序,版本= 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")) 

回答

6

由于Model.genres是一本字典,你应该

@Html.DropDownListFor(model => model.genres,new SelectList(Model.genres,"Key","Value")) 

这是因为枚举时,一个IDictionary<TKey, TValue>产生的KeyValuePair<TKey, TValue>枚举做到这一点。这是您需要查看的属性名称的类型。

+0

我刚才从这个问题问起,但我的工作不起作用:http://stackoverflow.com/questions/5326515/create-a-dropdown-list-for-mvc3-using-entity-framework- edmx-model-razor-vie – Xaisoft 2012-01-17 15:06:52

+0

我也听说Dictionary不是基于我链接的问题传递的最好的东西。我仍然没有找到最好的办法。 – Xaisoft 2012-01-17 15:08:00

+0

太棒了,你的解决方案工作。谢谢您的帮助。 – Xaisoft 2012-01-17 15:09:42