vendredi 4 novembre 2016

Equivalent of ViewData["MenuItem.StoreMenuId"] using ViewBag? ViewBag.MenuItem.StoreMenuId doesn't work

Is it possible to convert ViewData["MenuItem.StoreMenuId"] to ViewBag? I use ViewBags to store IEnumerable<SelectListItem> so I can bind to @Html.DropdownListFor in my views. This works fine if its a simple property that isn't nested (i.e., StoreMenuId):

ViewBag:

ViewBag.StoreMenuId = new SelectList(_db.StoreMenus.Where(m => m.Store.Id == model.StoreId), "Id", "Name");

DropDownListFor:

@Html.DropDownListFor(model => model.StoreMenuId, null, "", new { @class = "form-control" })


But what if the property is nested (i.e., MenuItem.StoreMenuId)? This doesn't work:

ViewBag:

ViewBag.MenuItem.StoreMenuId = new SelectList(_db.StoreMenus.Where(m => m.Store.Id == model.StoreId), "Id", "Name");

DropDownListFor:

@Html.DropDownListFor(model => model.MenuItem.StoreMenuId, null, "", new { @class = "form-control" })


What ends up working is changing ViewBag.MenuItem.StoreMenuId to ViewData["MenuItem.StoreMenuId"] This works:

ViewData:

ViewData["MenuItem.StoreMenuId"] = new SelectList(_db.StoreMenus.Where(m => m.Store.Id == model.StoreId), "Id", "Name");

DropDownListFor:

@Html.DropDownListFor(model => model.MenuItem.StoreMenuId, null, "", new { @class = "form-control" })

Aucun commentaire:

Enregistrer un commentaire