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!
The
Disabled
property will only be respected if you useIEnumerable<SelectListItem>
, notSelectList
(in theSelectList
contructor, you are only setting the properties ofValue
andText
) and in any case there is little point creatingIEnumerable<SelectListItem>
then creatingSelectList
from it when the helper only acceptsIEnumerable<SelectListItem>
then in the helper
Side note:
SelectList
does have an overloaded constructor that takesIEnumerable disabledValues
as a parameter (refer documentation)You are not taking into account
Disabled
property ofSelectListItem
, so -Return your model as typeof
instead of
And just bind as -
Hope this helps.