如何使下面的剃刀选择选项禁用选择选项?
@Html.DropDownListFor(model => model.RiskChange, new List<SelectListItem>
{
new SelectListItem{ Text="Low", Value = "Low" },
new SelectListItem{ Text="Medium", Value = "Medium" },
new SelectListItem{ Text="High", Value = "High" },
}, "Select", new { @class = "form-control" , onchange = "onRiskChange()" })
使它像这样工作。
<select class="form-control" name="RiskChange" >
<option selected="true" disabled="disabled">Select</option>
<option value="Low" >Low</option>
<option value="Medium" >Medium</option>
<option value="High" >High</option>
</select>
答案 0 :(得分:0)
不幸的是,默认SelectListItem
不具有disabled
属性的属性(并且无法从disabled
创建optionLabel
属性),因此无法设置{{1使用标准disabled
在option
元素中的}}属性。但是,您可以创建使用DropDownListFor
属性的自定义帮助程序:
disabled
用法
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));
}
}
注意:可以找到here来创建具有自定义属性的选项列表的类似方法。