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?
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);
}
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" })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With