HtmlHelpers.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Web;
  6. using System.Web.Mvc;
  7. namespace WePlatform.Helpers
  8. {
  9. public static class HtmlHelpers
  10. {
  11. private class ScriptBlock : IDisposable
  12. {
  13. private const string ScriptsKey = "PartialViewScripts";
  14. public static List<string> PartialViewScripts
  15. {
  16. get
  17. {
  18. if (HttpContext.Current.Items[ScriptsKey] == null)
  19. HttpContext.Current.Items[ScriptsKey] = new List<string>();
  20. return (List<string>)HttpContext.Current.Items[ScriptsKey];
  21. }
  22. }
  23. readonly WebViewPage _webPageBase;
  24. public ScriptBlock(WebViewPage webPageBase)
  25. {
  26. _webPageBase = webPageBase;
  27. _webPageBase.OutputStack.Push(new StringWriter());
  28. }
  29. public void Dispose()
  30. {
  31. PartialViewScripts.Add(((StringWriter)this._webPageBase.OutputStack.Pop()).ToString());
  32. }
  33. }
  34. public static IDisposable BeginScripts(this HtmlHelper helper)
  35. {
  36. return new ScriptBlock((WebViewPage)helper.ViewDataContainer);
  37. }
  38. public static MvcHtmlString PartialViewScripts(this HtmlHelper helper)
  39. {
  40. return MvcHtmlString.Create(string.Join(Environment.NewLine, ScriptBlock.PartialViewScripts.Select(s => s.ToString())));
  41. }
  42. }
  43. }