I am trying to fix a bug in an existing application, and my MVC ViewBag skills are limited. First off, I don’t have the time to refactor and change the code from a ViewBag to a ViewModel, although that would be my preferred approach.
I want to populate a DropDownList from an object in the ViewBag. The code is here:
if(Model != null && Model.WarehouseId != null && !Model.WarehouseId.Equals(String.Empty))
{
@Html.DropDownListFor(m => m.WarehouseId, (IEnumerable<SelectListItem>)ViewBag.WarehouseCodes)<br /> //<---
}
else
{
@Html.DropDownListFor(m => m.WarehouseId, (IEnumerable<SelectListItem>)ViewBag.WarehouseCodes, "")<br />
}
In the case that the WarehouseID is not String.Empty, I ONLY want to load that value into the DropDownList. I’m open to a C# or jQuery answer to this question.
Thanks in advance for any help offered!
If you forget those skills it would be even better for you. Just kidding, they could be useful in order to know what not to do in an ASP.NET MVC application 🙂
Anyway:
Another approach is to handle this case in your controller action:
and in your view you could now replace the
ifwith: