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

梦想的初衷 提交于 2019-12-10 09:40:47

问题


I am trying to create a dropdown list with a few options disabled so that they are not selectable. Here is my code:

var places = new SelectList(new List<SelectListItem>
{
    new SelectListItem { Selected = false, Text = "Virgin Islands", Value = "Virgin Islands"},
    new SelectListItem { Selected = false, Text = "", Value = "", Disabled= true},
    new SelectListItem { Selected = false, Text = "Canada", Value = "Canada", Disabled= true},
    new SelectListItem { Selected = false, Text = "", Value = "", Disabled= true},
    new SelectListItem { Selected = false, Text = "Other", Value = "Other"},
}, "Value", "Text");

However, generated HTML for the disabled SelectListItem is merely:

<option value=""></option>

How can I generate the following HTML

<option disabled="disabled"></option>

from SelectListItem?

Thanks!


回答1:


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)




回答2:


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.



来源:https://stackoverflow.com/questions/29424365/net-mvc-5-2-3-how-to-create-a-disabled-option-out-of-selectlistitem

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