Skip to content Skip to sidebar Skip to footer

How To Dynamic Setting Html.dropdownlist Attribute Disabled In Razorview?

Here it is my Drop-down: @Html.DropDownList('OptionType', selectList, new { @class = 'form-control', name = 'OptionType',@disabled = 'disabled' }) The above code can set DropDownL

Solution 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" })
}

Solution 2:

You can try below code:

creating an extension for HtmlHelper:

publicstaticclassHtmlExtensions
{
    publicstatic 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" });
        elsereturn html.DropDownListFor(expression, selectList, optionText);

    }
}

In razor view:

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

Post a Comment for "How To Dynamic Setting Html.dropdownlist Attribute Disabled In Razorview?"