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 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.