I'm trying to get the drop down list to have my item selected when there is an item, but it never does. I've Googled this and tried many different methods, but they all seem to use a ViewModel containing the list instead of using ViewBag, but I would like to stick to the ViewBag if possible.
My controller:
[HttpGet]
public ActionResult Index(int? id)
{
ViewBag.SelectList = new SelectList(rep.GetItemList(), "id", "type");
if (id.HasValue)
{
var model = rep.GetItemByID(id.Value);
if ( model != null )
{
return View(model);
}
}
return View();
}
My View:
<div class="editor-field">
@Html.DropDownListFor(model => model.itemID, (SelectList)ViewBag.SelectList)
@Html.ValidationMessageFor(model => model.itemID)
</div>
This doesn't have my item selected in the DropDownList, and I've also tried having a list in the ViewBag and then constructing the SelectList in the View, which some posts say should solve the problem:
<div class="editor-field">
@Html.DropDownListFor(model => model.itemID, new SelectList(ViewBag.SelectList, "id", "type", Model.itemID))
@Html.ValidationMessageFor(model => model.itemID)
</div>
But none of it seems to work. So I was wondering if there is anyone where that is able to spot what I'm doing wrong?