MvcHtmlHelpers.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Web;
  7. using System.Web.Mvc;
  8. namespace ShwasherSys
  9. {
  10. public static class HtmlHelpers
  11. {
  12. private class ScriptBlock : IDisposable
  13. {
  14. private const string ScriptsKey = "PartialViewScripts";
  15. public static List<string> PartialViewScripts
  16. {
  17. get
  18. {
  19. if (HttpContext.Current.Items[ScriptsKey] == null)
  20. HttpContext.Current.Items[ScriptsKey] = new List<string>();
  21. return (List<string>)HttpContext.Current.Items[ScriptsKey];
  22. }
  23. }
  24. readonly WebViewPage _webPageBase;
  25. public ScriptBlock(WebViewPage webPageBase)
  26. {
  27. _webPageBase = webPageBase;
  28. _webPageBase.OutputStack.Push(new StringWriter());
  29. }
  30. public void Dispose()
  31. {
  32. PartialViewScripts.Add(((StringWriter)_webPageBase.OutputStack.Pop()).ToString());
  33. }
  34. }
  35. public static IDisposable BeginScripts(this HtmlHelper helper)
  36. {
  37. return new ScriptBlock((WebViewPage)helper.ViewDataContainer);
  38. }
  39. public static MvcHtmlString PartialViewScripts(this HtmlHelper helper)
  40. {
  41. return MvcHtmlString.Create(string.Join(Environment.NewLine, ScriptBlock.PartialViewScripts.Select(s => s.ToString())));
  42. }
  43. public static List<SelectListItem> TranSelectItems<T>(List<T> tList, string showColumn, string valueColumn) where T : new()
  44. {
  45. List<SelectListItem> list = new List<SelectListItem>();
  46. foreach (var li in tList)
  47. {
  48. var type = typeof(T);
  49. PropertyInfo showPro = type.GetProperty(showColumn);
  50. var show = showPro?.GetValue(li);
  51. PropertyInfo valuePro = type.GetProperty(valueColumn);
  52. var value = valuePro?.GetValue(li);
  53. list.Add(new SelectListItem()
  54. {
  55. Text = show?.ToString(),
  56. Value = value?.ToString()
  57. });
  58. }
  59. return list;
  60. }
  61. }
  62. }