Reputation: 145
Building the SelectList
public SelectList DummyList()
{
List<SelectListItem> list = new List<SelectListItem>();
list.Add(new SelectListItem { Value = "0", Text = "---Select--", Disabled = false });
list.Add(new SelectListItem { Value = "Uno", Text = "Uno", Disabled = false });
list.Add(new SelectListItem { Value = "Dos", Text = "Dos", Disabled = true});
list.Add(new SelectListItem { Value = "Tres", Text = "Tres", Disabled = false });
list.Add(new SelectListItem { Value = "Cuatro", Text = "Cuatro", Disabled = false });
return new SelectList(list, "Value", "Text", "---Select--");
}
Binding the Select List to the model
model.ProductsModel.Model = new DummyDropDown().DummyList();
Displaying the view
@Html.DropDownListFor(model => model.Model, Model.Model, htmlAttributes: new { @class = "dropdown ", @style = "width:50%;" })
Html Result
<select id="Model" class="dropdown " style="width:50%;" name="Model">
<option value="0">---Select--</option>
<option value="Uno">Uno</option>
<option value="Dos">Dos</option>
<option value="Tres">Tres</option>
<option value="Cuatro">Cuatro</option>
</select>
View
The Select List is displaying all the items enabled when in reality option "Dos" should be disabled
<option value="Dos" disabled>Dos</option>
according to the properties.
If someone can explain why to me, or tell me what is wrong with the code. Is there any other way to achieve this? I need item "Dos" to be disabled (grayed out).
Thanks in advance.
Upvotes: 6
Views: 6657
Reputation:
Try changing your method to
public IEnumerable<SelectListItem> DummyList()
{
List<SelectListItem> list = new List<SelectListItem>();
....
list.Add(new SelectListItem { Value = "Dos", Text = "Dos", Disabled = true});
....
return list;
}
and make ProductsModel.Model
typeof IEnumerable<SelectListItem>
rather than SelectList
Currently your creating a new SelectList
based on your list using the properties Value
and Text
only (not taking into account the Disabled
property). Alternatively you can use one of the SelectList overloads that accepts parameter IEnumerable
of disabled values
Upvotes: 14