如何在RazorView中禁用动态设置Html.DropDownList属性?

时间:2017-05-31 03:13:03

标签: c# asp.net-mvc html-select

这是我的下拉:

@Html.DropDownList("OptionType", selectList, new { @class = "form-control", name = "OptionType",@disabled = "disabled" })

上面的代码可以设置DropDownList被禁用,但我想动态设置disabled属性和模型中的bool值。换句话说,如果bool value = true,则启用DropDownList,否则禁用DropDownList。如何实现呢?

2 个答案:

答案 0 :(得分:2)

如果要根据模型的属性禁用下拉列表:

@if(Model.DisableDropdown)
{ 
    @Html.DropDownList("OptionType", selectList, new { @disabled = "disabled", @class = "form-control" })
}
else
{
    @Html.DropDownList("OptionType", selectList, new { @class = "form-control" })
}

答案 1 :(得分:1)

您可以尝试以下代码:

为HtmlHelper创建扩展程序:

public static class HtmlExtensions
{
    public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string optionText, bool IsDisabled)
    {
        if (IsDisabled)   
            return html.DropDownListFor(expression, selectList, optionText, new { @disabled = "disabled" });
        else
            return html.DropDownListFor(expression, selectList, optionText);

    }
}

在剃须刀视图中:

@Html.DropDownListFor(model => model.Type, Model.Types, "", Model.IsDisabled)