I would like to create a HtmlHelper that can be used on IEnumerable properties.
The aim is to use it like this:
@Html.DisplayForEnumerable(m => m.EnumerableItemsProperty, "ViewTemplateName");
If possible I would like to use the
m => m.Items lambda syntax (as opposed to passing through
This is my best effort so far. But I'm not sure how to get the
items variable from the expression parameter.
I suspect I may have to use something like
IEnumerable<TValue> as the return type of the expression, but I'm quite new to generics and I've no idea how to implement this.
public static MvcHtmlString DisplayForEnumerable<TModel>(this HtmlHelper<TModel> html, Expression<Func<TModel, IEnumerable>> expression, string templateName, object additonalViewData = null)
var sb = new StringBuilder();
// how to get items variable?
foreach (var item in items)
var item1 = item;
sb.Append(html.DisplayFor(m => item1, templateName, additonalViewData));
To clarify - I am taking this approach because I would like to be able so specify differnt templates for the same model. And the normal
DisplayFor() enumeration does not occur if you specify a particular template.
I know I could just enumerate through manually, but I'd rather use this method unless someone more knowledgable advises otherwise.