3

I have a database table called Genre with the following fields:

  • Id (Seeded Primary Key)
  • Name (Name of Genre - Romance, Western, etc...)

I have a Model class called GenreDropDownModel which contains teh following code:

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

}

My Controller Write action is declared as:

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

Finally, my view Write.cshtml is where I get the following error:

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]]' does not contain a property with the name 'Id'.

@model Stories.Models.GenreDropDownModel

@{
    ViewBag.Title = "Write";
}

<h2>Write</h2>

@Html.DropDownListFor(model => model.genres,new SelectList(Model.genres,"Id","Name"))
Xaisoft
  • 45,655
  • 87
  • 279
  • 432

1 Answers1

7

Since Model.genres is a dictionary, you should do this with

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

This is because when enumerated, an IDictionary<TKey, TValue> produces an enumeration of KeyValuePair<TKey, TValue>. That's the type you need to look at to see how the properties are named.

Jon
  • 428,835
  • 81
  • 738
  • 806
  • I was going off of this question asked from before, but mine does not work: http://stackoverflow.com/questions/5326515/create-a-dropdown-list-for-mvc3-using-entity-framework-edmx-model-razor-vie – Xaisoft Jan 17 '12 at 15:06
  • I also heard that Dictionary is not the best thing to pass based on the question I linked. I still have not found the best way. – Xaisoft Jan 17 '12 at 15:08
  • @Xaisoft: I was just reading the answer you link to and it simply appears to be wrong (in the sense that the property names will not work). Don't worry about the dictionaries for now, it's not anything too important. – Jon Jan 17 '12 at 15:11