如何在 Razor 视图中禁用动态设置 Html.DropDownList 属性?
how to Dynamic setting Html.DropDownList attribute disabled in RazorView?
这是我的下拉菜单:
@Html.DropDownList("OptionType", selectList, new { @class = "form-control", name = "OptionType",@disabled = "disabled" })
上面的代码可以设置 DropDownList 是禁用的,但是我想用模型中的 bool 值动态设置禁用属性。换句话说,如果 bool value = true,则启用 DropDownList,否则禁用 DropDownList。如何实现?
如果您想根据模型的 属性 禁用下拉菜单:
@if(Model.DisableDropdown)
{
@Html.DropDownList("OptionType", selectList, new { @disabled = "disabled", @class = "form-control" })
}
else
{
@Html.DropDownList("OptionType", selectList, new { @class = "form-control" })
}
您可以试试下面的代码:
为 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)
这是我的下拉菜单:
@Html.DropDownList("OptionType", selectList, new { @class = "form-control", name = "OptionType",@disabled = "disabled" })
上面的代码可以设置 DropDownList 是禁用的,但是我想用模型中的 bool 值动态设置禁用属性。换句话说,如果 bool value = true,则启用 DropDownList,否则禁用 DropDownList。如何实现?
如果您想根据模型的 属性 禁用下拉菜单:
@if(Model.DisableDropdown)
{
@Html.DropDownList("OptionType", selectList, new { @disabled = "disabled", @class = "form-control" })
}
else
{
@Html.DropDownList("OptionType", selectList, new { @class = "form-control" })
}
您可以试试下面的代码:
为 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)