asp.net-mvc-3 - ASP.NET MVC 3 中 DropDownListFor 的数据绑定(bind)错误?

标签 asp.net-mvc-3 entity-framework-4 html.dropdownlistfor

我有一个名为 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/

相关文章:

asp.net-mvc - asp.net mvc - ActionLink 的呈现不一致

asp.net-mvc-3 - 在MVC3非强制性远程验证上强制重新验证

c# - 格式化 List<T> 以连接字段

javascript - 使用 select 选项仅显示第一个 <td> 的所需值 =""的表行

javascript - 如何使用内存流在上传之前预览图像

c# - 模型绑定(bind)找不到继承的接口(interface)属性

c# - 许多查询和同一连接的打开/关闭太多

c# - 无法删除该对象,因为在 ObjectStateManager 中找不到它

c# - ASP.NET MVC + 填充下拉列表

c# - 如何写一个简单的 Html.DropDownListFor()?