how to Dynamic setting Html.DropDownList attribute disabled in RazorView? [closed]

允我心安 提交于 2019-12-25 16:07:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!