PageRenderTime 44ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/ThinkEmailFomatter/Utilities/ViewHelper.cs

https://bitbucket.org/nicdao/frg-think-emailformatter
C# | 58 lines | 43 code | 5 blank | 10 comment | 3 complexity | df69a9198c80a58ed4dc1ae3a077c2cb MD5 | raw file
Possible License(s): BSD-3-Clause
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6. using ThinkEmailFormatter.Models.Extensions;
  7. using System.IO;
  8. using System.Text;
  9. using ThinkEmailFormatter.Models;
  10. namespace ThinkEmailFormatter.Utilities
  11. {
  12. public class ViewHelper
  13. {
  14. private readonly HttpContextBase _httpContext;
  15. public ViewHelper(HttpContextBase httpContext)
  16. {
  17. _httpContext = httpContext;
  18. }
  19. public IEnumerable<Template> GetTemplates()
  20. {
  21. // Get the full path of the View "Request"
  22. string requestViewPath = _httpContext.Request.MapPath(@"~/Views/Template/Templates");
  23. // Get all "cshtml" files from that folder
  24. string[] filePaths = Directory.GetFiles(requestViewPath, "*.cshtml");
  25. // For each files, get rid of the extension file
  26. return filePaths.Select(f => new Template() { Name = f.Split('\\').Last().Split('.').First() }).Where(t => string.Compare(t.Name, "_viewstart", true) != 0);
  27. }
  28. /// <summary>
  29. /// Convert a view to a string
  30. /// </summary>
  31. /// <typeparam name="T"></typeparam>
  32. /// <param name="viewName"></param>
  33. /// <param name="model"></param>
  34. /// <returns></returns>
  35. public string RenderViewToString<T>(ControllerContext controllerContext, string viewName, T model)
  36. {
  37. var view = ViewEngines.Engines.FindView(controllerContext, viewName, null).View;
  38. if (view != null)
  39. {
  40. var sb = new StringBuilder();
  41. using (var writer = new StringWriter(sb))
  42. {
  43. var viewContext = new ViewContext(controllerContext, view,
  44. new ViewDataDictionary(model), new TempDataDictionary(), writer);
  45. view.Render(viewContext, writer);
  46. writer.Flush();
  47. }
  48. return sb.ToString();
  49. }
  50. return string.Empty;
  51. }
  52. }
  53. }