Monthly Archives: March 2017

Disable Html.DropDownListFor if only one item in dropdown


@Html.DropDownListFor(m => m.SelectedValue,
new SelectList(Model.CollectionOfItemsForDropdown, "ValueField", "NameField"),
@Model.CollectionOfItemsForDropdown.Count > 1
? (object)new { @class = "form-control", required = "true", }
: new { @class = "form-control", required = "true", disabled = "disabled" })

You have to use the conditional operator here for the anonymous objects because the dropdown list will be disabled if the word ‘disabled’ is rendered in the tag in any way.