Possible bug in Html.DropDownList, selected values not reflecting?

时光怂恿深爱的人放手 提交于 2019-12-04 22:01:32

Ok... I just fixed it.

I changed around my view model to use a CategoryId instead of a Category slug. So now, my view looks like:

@Html.DropDownListFor(a => a.CategoryId, Model.CategoryOptions, new { @class = "ask-category-field" })

I think the model value being select (in this case, a => a.CategoryId) has to have the same type as the selected 'value.' (I will refine this explanation when I get more time to go over the framework code.) But clever coding indeed :) Hats of to ASP.NET MVC devs.

Now, it works perfectly as expect and also retains changes to the selected item across a PRG lifecycle.

Hope this helps someone.

The selected property on a dropdown item doesn't actually set the dropdown item to be selected in the HTML.

I've experienced this problem myself before.

My solution to this was an extension method on the ViewDataDictionary that allows you to set the value of a given select list based on the selected item & a string Id of the select list.

public static void SetSelectedValueFor(this ViewDataDictionary viewDataDictionary, string key, IEnumerable<SelectListItem> items)
        {
            //  HACK: Store the selected item value in ViewData so that the DropDownListFor knows which one should be selected.
            //  It's a bit of a hack but it seems to be the only way I can do it since DropdownListFor ignores the Selected property on SelectListItem.
            var x = items.Where(c => c.Selected).FirstOrDefault();
            if (x != null)
            {
                viewDataDictionary[key] = x.Value;
            }
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!