问题
Here it is my Drop-down:
@Html.DropDownList("OptionType", selectList, new { @class = "form-control", name = "OptionType",@disabled = "disabled" })
The above code can set DropDownList is disabled,but I want to dynamic set disabled attribute with a bool value from model. In other words if bool value = true, DropDownList is enable, else DropDownList is disabled. how to achieve it?
回答1:
If you want to disable the dropdown based on a property of your model:
@if(Model.DisableDropdown)
{
@Html.DropDownList("OptionType", selectList, new { @disabled = "disabled", @class = "form-control" })
}
else
{
@Html.DropDownList("OptionType", selectList, new { @class = "form-control" })
}
回答2:
You can try below code:
creating an extension for 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);
}
}
In razor view:
@Html.DropDownListFor(model => model.Type, Model.Types, "", Model.IsDisabled)
来源:https://stackoverflow.com/questions/44275015/how-to-dynamic-setting-html-dropdownlist-attribute-disabled-in-razorview