Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add additional htmlattributes in extension for DropDownListFor

Tags:

asp.net-mvc

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?

like image 481
AnonyMouse Avatar asked Mar 08 '12 20:03

AnonyMouse


Video Answer


2 Answers

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);
}
like image 160
archil Avatar answered Sep 27 '22 22:09

archil


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" })
like image 40
Dmitry Efimenko Avatar answered Sep 27 '22 21:09

Dmitry Efimenko