Unfortunately default SelectListItem
does not have property for disabled
attribute (and there is no way to create disabled
attribute from optionLabel
), so you cannot set disabled
attribute in option
element using standard DropDownListFor
. However, you can create custom helper which uses disabled
attribute for that purpose:
public static class CustomHelper
{
public static MvcHtmlString CustomDropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string optionLabel, object htmlAttributes)
{
if (expression == null)
{
throw new ArgumentNullException("expression");
}
ModelMetadata metadata = ModelMetadata.FromLambdaExpression<TModel, TProperty>(expression, htmlHelper.ViewData);
string expressionName = ExpressionHelper.GetExpressionText(expression);
string fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(expressionName);
if (String.IsNullOrEmpty(fullName))
{
throw new ArgumentException("name");
}
var builder = new TagBuilder("select");
// add default attributes here
builder.Attributes.Add("name", fullName);
// merge htmlAttributes here
if (htmlAttributes != null)
{
var attr = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
builder.MergeAttributes(attr);
}
var sb = new StringBuilder();
// if option label contains any string value,
// create option placeholder with disabled and selected attribute
if (!string.IsNullOrEmpty(optionLabel))
{
sb.Append(string.Format("<option selected='true' disabled='disabled'>{0}</option>", optionLabel));
}
foreach (var item in selectList)
{
sb.Append(string.Format("<option value='{0}'>{1}</option>", item.Value, item.Text));
}
builder.InnerHtml = sb.ToString();
return MvcHtmlString.Create(builder.ToString(TagRenderMode.Normal));
}
}
Usage
@Html.CustomDropDownListFor(model => model.RiskChange, Model.RiskOptions, "Select", new { @class = "form-control" , onchange = "onRiskChange()" })
Note: A similar way to create option lists with custom attributes can be found here.
Reference: SelectExtensions.DropDownListFor() method