Is the following helper idiomatic ASP.NET MVC? All the built-in DropDownListFor
helpers only accept IEnumerable<SelectListItem>
. If the Model doesn't have this list, but an IEnumerable<SomeEntity>
, avoiding this conversion in the Razor template seems to require some more of its helpers.
namespace CompanyName.ProjectName.PresentationLayer.Helpers
{
// ...documentation omitted...
public static MvcHtmlString DropDownListFor<TModel, TElem>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, string>> expression,
IEnumerable<TElem> elements,
Func<TElem, string> valueFunc,
Func<TElem, string> textFunc
)
{
ModelMetadata metadata =
ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
IEnumerable<SelectListItem> items =
elements.Select(elem => new SelectListItem()
{
Value = valueFunc(elem),
Text = textFunc(elem),
Selected = elem.Equals(metadata.Model)
});
return htmlHelper.DropDownListFor<TModel, string>(expression, items);
}
}