Advertisement
Guest User

Untitled

a guest
Dec 8th, 2015
630
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.23 KB | None | 0 0
  1. public static class HtmlHelperExtensions
  2. {
  3.     public static MvcHtmlString EditorForMany<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, IEnumerable<TValue>>> expression, string templateName = null, object data = null) where TModel : class
  4.     {
  5.         StringBuilder sb = new StringBuilder();
  6.  
  7.         // Get the items from ViewData
  8.         var items = expression.Compile()(html.ViewData.Model);
  9.         var fieldName = ExpressionHelper.GetExpressionText(expression);
  10.         //var htmlFieldPrefix = html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix;
  11.         //var fullHtmlFieldPrefix = String.IsNullOrEmpty(htmlFieldPrefix) ? fieldName : String.Format("{0}.{1}", htmlFieldPrefix, fieldName);
  12.         int index = 0;
  13.  
  14.         foreach (TValue item in items)
  15.         {
  16.             // Much gratitude to Matt Hidinger for getting the singleItemExpression.
  17.             // Current html.DisplayFor() throws exception if the expression is anything that isn't a "MemberAccessExpression"
  18.             // So we have to trick it and place the item into a dummy wrapper and access the item through a Property
  19.             var dummy = new { Item = item };
  20.  
  21.             // Get the actual item by accessing the "Item" property from our dummy class
  22.             var memberExpression = Expression.MakeMemberAccess(Expression.Constant(dummy), dummy.GetType().GetProperty("Item"));
  23.  
  24.             // Create a lambda expression passing the MemberExpression to access the "Item" property and the expression params
  25.             var singleItemExpression = Expression.Lambda<Func<TModel, TValue>>(memberExpression,
  26.                                                                                 expression.Parameters);
  27.  
  28.             // Now when the form collection is submitted, the default model binder will be able to bind it exactly as it was.
  29.             //var itemFieldName = String.Format("{0}[{1}]", fullHtmlFieldPrefix, index++);
  30.             var itemFieldName = String.Format("{0}[{1}]", fieldName, index++);
  31.             string singleItemHtml = html.EditorFor(singleItemExpression, templateName, itemFieldName, data).ToString();
  32.             sb.AppendFormat(singleItemHtml);
  33.         }
  34.  
  35.         return new MvcHtmlString(sb.ToString());
  36.     }
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement