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"))

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I was going off of this question asked from before, but mine does not work: stackoverflow.com/questions/5326515/…
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: 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.