Reputation: 46601
I have a database table called Genre with the following fields:
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"))
Upvotes: 3
Views: 3489
Reputation: 437406
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.
Upvotes: 7