I\'m using ASP.NET MVC 3, and just ran into a \'gotcha\' using the DropDownListFor
HTML Helper.
I do this in my Controller:
ViewBag.Ship
I was just hit by this limitation and figured out a simple workaround. Just defined extension method that internally generates SelectList
with correct selected item.
public static class HtmlHelperExtensions
{
public static MvcHtmlString DropDownListForEx(
this HtmlHelper htmlHelper,
Expression> expression,
IEnumerable selectList,
object htmlAttributes = null)
{
var selectedValue = expression.Compile().Invoke(htmlHelper.ViewData.Model);
var selectListCopy = new SelectList(selectList.ToList(), nameof(SelectListItem.Value), nameof(SelectListItem.Text), selectedValue);
return htmlHelper.DropDownListFor(expression, selectListCopy, htmlAttributes);
}
}
The best thing is that this extension can be used the same way as original DropDownListFor
:
@for(var i = 0; i < Model.Items.Count(); i++)
{
@Html.DropDownListForEx(x => x.Items[i].CountryId, Model.AllCountries)
}