AnonyMouse
AnonyMouse

Reputation: 18630

How to add additional htmlattributes in extension for DropDownListFor

I'm trying to write an extension for DropDownListFor:

public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, object htmlAttributes, bool enabled)
{
    return htmlHelper.DropDownListFor(expression, selectList, null /* optionLabel */, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
}

What I want to achieve is if enabled is false no change but if enabled is true I want to add @disabled="disabled" to the html attributes before giving them to AnonymousObjectToHtmlAttributes.

Any ideas on how to do this?

Upvotes: 11

Views: 19018

Answers (2)

archil
archil

Reputation: 39491

Simple! HtmlHelper.AnonymousObjectToHtmlAttributes returns RouteValueDictionary. You can add value to that dictionary, you do not need to add property to anonymous object.

public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, object htmlAttributes, bool enabled)
{
    var attrs = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
    if (!enabled)
    {
        attrs.Add("disabled", "disabled");
    }
    return htmlHelper.DropDownListFor(expression, selectList, null /* optionLabel */, attrs);
}

Upvotes: 33

Dmitry Efimenko
Dmitry Efimenko

Reputation: 11203

Solution by archil works. However, for what you are trying to do writing an extension is an overkill.

Just write in your view something like:

@Html.DropDownListFor(m => m.Id, Model.Values, new { disabled = "disabled" })

Upvotes: 2

Related Questions