如何在Razor View中禁用动态设置Html.DropDownList属性? [关闭]

问题描述 投票:0回答:2

这是我的下拉:

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

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

c# asp.net-mvc html-select
2个回答
2
投票

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

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

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)
© www.soinside.com 2019 - 2024. All rights reserved.