Donate

@Html.EnumDropDownListFor() Helper With Html Attributes In ASP.NET MVC

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. :-)

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.