Last active
September 21, 2017 09:52
-
-
Save codingbadger/8d652ea4fbe55a4ee84b9415dd867737 to your computer and use it in GitHub Desktop.
EditorFor and DisplayFor when using custom templates and IEnumerables
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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