.Net MVC 5.2.3: how to create a disabled option ou

2019-07-20 13:20发布

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!

2条回答
ら.Afraid
2楼-- · 2019-07-20 14:05

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)

查看更多
【Aperson】
3楼-- · 2019-07-20 14:14

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.

查看更多
登录 后发表回答