Guest User

Untitled

a guest
Jan 16th, 2019
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6.  
  7. namespace MVCWebTest.Helpers
  8. {
  9. public static class HtmlHelper
  10. {
  11. public static IDisposable BeginCollectionItem<TModel>(this HtmlHelper<TModel> html, string collectionName)
  12. {
  13. string itemIndex = Guid.NewGuid().ToString();
  14. string collectionItemName = string.Format("{0}[{1}]", collectionName, itemIndex);
  15.  
  16. TagBuilder indexField = new TagBuilder("input");
  17. indexField.MergeAttributes(new Dictionary<string, string>() {
  18. { "name", string.Format("{0}.Index", collectionName) },
  19. { "value", itemIndex },
  20. { "type", "hidden" },
  21. { "autocomplete", "off" }
  22. });
  23.  
  24. html.ViewContext.Writer.WriteLine(indexField.ToString(TagRenderMode.SelfClosing));
  25. return new CollectionItemNamePrefixScope(html.ViewData.TemplateInfo, collectionItemName);
  26. }
  27.  
  28. private class CollectionItemNamePrefixScope : IDisposable
  29. {
  30. private readonly TemplateInfo _templateInfo;
  31. private readonly string _previousPrefix;
  32.  
  33. public CollectionItemNamePrefixScope(TemplateInfo templateInfo, string collectionItemName)
  34. {
  35. _templateInfo = templateInfo;
  36.  
  37. _previousPrefix = templateInfo.HtmlFieldPrefix;
  38. templateInfo.HtmlFieldPrefix = collectionItemName;
  39. }
  40.  
  41. public void Dispose()
  42. {
  43. _templateInfo.HtmlFieldPrefix = _previousPrefix;
  44. }
  45. }
  46. }
  47. }
Add Comment
Please, Sign In to add comment