不幸的是违约
SelectListItem
没有的属性
disabled
属性(无法创建
残疾人
属性来自
optionLabel
),所以你不能设置
残疾人
属性在
option
元素使用标准
DropDownListFor
. 但是,您可以创建使用
残疾人
为此目的的属性:
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));
}
}
用法
@Html.CustomDropDownListFor(model => model.RiskChange, Model.RiskOptions, "Select", new { @class = "form-control" , onchange = "onRiskChange()" })
注:
可以找到使用自定义属性创建选项列表的类似方法
here
.
参考文献:
SelectExtensions.DropDownListFor() method