ASP.NET MVC DropDownListFor not selecting value from model

后端 未结 5 686
梦毁少年i
梦毁少年i 2020-11-30 09:11

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         


        
5条回答
  •  無奈伤痛
    2020-11-30 09:34

    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)
    }
    

提交回复
热议问题