Thursday, October 20, 2016

@Html.EnumDropDownListFor() with Html Attributes

Hello,
I did some research on how to use enums as model for DropDownListFor() for a current application and will format it with Bootstrap classes. For ASP.NET MVC 4, it does not have that kind of helper yet. Luckily, I found an article here Creating a DropDownList helper for enums which supports enums as data source. However, it does not have an argument where in you can pass a boostrap class such as form-control. To achieve the desired output, all you need to do is modify the helper and add another parameter for html attributes which will then be used by the DropDownListFor().
public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, 
 Expression<Func<TModel, TEnum>> expression, object htmlAttributes)
{
 ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
 IEnumerable<TEnum> values = Enum.GetValues(typeof(TEnum)).Cast<TEnum>();

 IEnumerable<SelectListItem> items = values.Select(value => new SelectListItem
          {
           Text = value.ToString(),
           Value = value.ToString(),
           Selected = value.Equals(metadata.Model)
          });

 return htmlHelper.DropDownListFor(expression, items, htmlAttributes);
}

Thanks to the author of this extension. :-)

0 comments:

Post a Comment