After some time trying get the example on Pg. 105 working, I'm crying Uncle!
In debug I can see the ViewBag.Genres populated with SelectListItems, but I can't figure out how to get them into a SelectList that DropDownList can use. Thanks, to anyone who might shed light on this.
My Controller code is (straight from the book)
Code:
// ~/Controllers/AlbumController.cs
{
public class AlbumController : Controller
{
private MusicStoreDB storeDB = new MusicStoreDB();
//
// GET: /Album/Edit/#
public ActionResult Edit(int id)
{
var album = storeDB.Albums.Single(a => a.AlbumId == id);
// Page 105 - Use LINQ to project Generes into SelectListItem
ViewBag.Genres = storeDB.Genres
.OrderBy(g => g.Name)
.AsEnumerable()
.Select(g => new SelectListItem
{
Text = g.Name,
Value = g.GenreId.ToString(),
Selected = album.GenreId == g.GenreId
});
return View(album);
}
}
}
My View Code is ...
Code:
@* ~/Views/Album/Edit.cshtml *@
@model MvcMusicStore.Models.Album
@using (Html.BeginForm())
{
@Html.ValidationSummary(excludePropertyErrors: true)
<fieldset>
<legend>Edit Album</legend>
<p>
@Html.Label("GenreId")
@Html.DropDownList("GenreId", ViewBag.Genres as SelectList)
</p>
<p>
@Html.Label("Title")
@Html.TextBox("Title", Model.Title)
</p>
<input type="submit" value="Save" />
</fieldset>
}
The view throws an exception at
@Html.DropDownList ..
Code:
The ViewData item that has the key 'GenreId' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'.