.Net MVC 5.2.3: how to create a disabled option out of SelectListItem?

自闭症网瘾萝莉.ら 提交于 2019-12-06 04:54:56

The Disabled property will only be respected if you use IEnumerable<SelectListItem>, not SelectList (in the SelectList contructor, you are only setting the properties of Value and Text) and in any case there is little point creating IEnumerable<SelectListItem> then creating SelectList from it when the helper only accepts IEnumerable<SelectListItem>

var places = new List<SelectListItem>
{
    new SelectListItem { Selected = false, Text = "Virgin Islands", Value = "Virgin Islands"},
    new SelectListItem { Selected = false, Text = "", Value = "", Disabled= true},
    ....
};

then in the helper

@Html.DropDownList(m => m.YourProperty, model.places) // or (IEnumerable<SelectListItem>)ViewBag.places

Side note: SelectList does have an overloaded constructor that takes IEnumerable disabledValues as a parameter (refer documentation)

You are not taking into account Disabled property of SelectListItem, so -

Return your model as typeof

IEnumerable<SelectListItem>

instead of

SelectList

And just bind as -

@Html.DropDownList(m => m.Prop, model.places);

Hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!