Skip to content

Instantly share code, notes, and snippets.

@codingbadger
Last active September 21, 2017 09:52
Show Gist options
  • Save codingbadger/8d652ea4fbe55a4ee84b9415dd867737 to your computer and use it in GitHub Desktop.
Save codingbadger/8d652ea4fbe55a4ee84b9415dd867737 to your computer and use it in GitHub Desktop.
EditorFor and DisplayFor when using custom templates and IEnumerables
public static class MvcExtensions
{
public static MvcHtmlString EditorForEnumerable<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, IEnumerable<TValue>>> expression, string templateName)
{
var fieldName = html.NameFor(expression).ToString();
var items = expression.Compile()(html.ViewData.Model);
return new MvcHtmlString(string.Concat(items.Select((item, i) => html.EditorFor(m => item, templateName, fieldName + '[' + i + ']'))));
}
public static MvcHtmlString DisplayForEnumerable<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, IEnumerable<TValue>>> expression, string templateName)
{
var fieldName = html.NameFor(expression).ToString();
var items = expression.Compile()(html.ViewData.Model);
return new MvcHtmlString(string.Concat(items.Select((item, i) => html.DisplayFor(m => item, templateName, fieldName + '[' + i + ']'))));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment