【问题标题】:Databinding error with DropDownListFor in ASP.NET MVC 3?ASP.NET MVC 3 中 DropDownListFor 的数据绑定错误?
【发布时间】:2012-01-17 15:00:09
【问题描述】:

我有一个名为 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);
        }
    }

}

我的控制器Write 操作声明为:

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

最后,我的视图 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"))

【问题讨论】:

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


    【解决方案1】:

    由于Model.genres 是一个字典,你应该这样做

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

    这是因为在枚举时,IDictionary&lt;TKey, TValue&gt; 会生成 KeyValuePair&lt;TKey, TValue&gt; 的枚举。这是您需要查看的类型以了解属性是如何命名的。

    【讨论】:

    • 我之前提出过这个问题,但我的问题不起作用:stackoverflow.com/questions/5326515/…
    • 我还听说根据我链接的问题,字典不是最好的传递方法。我还没有找到最好的方法。
    • @Xaisoft:我只是在阅读您链接到的答案,它似乎是错误的(从某种意义上说,属性名称不起作用)。暂时不用担心字典,这不是什么太重要的事情。
    猜你喜欢
    • 2011-06-30
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 2017-03-03
    • 2011-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多