/ThinkEmailFomatter/Utilities/ViewHelper.cs
C# | 58 lines | 43 code | 5 blank | 10 comment | 3 complexity | df69a9198c80a58ed4dc1ae3a077c2cb MD5 | raw file
Possible License(s): BSD-3-Clause
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using ThinkEmailFormatter.Models.Extensions;
- using System.IO;
- using System.Text;
- using ThinkEmailFormatter.Models;
- namespace ThinkEmailFormatter.Utilities
- {
- public class ViewHelper
- {
- private readonly HttpContextBase _httpContext;
- public ViewHelper(HttpContextBase httpContext)
- {
- _httpContext = httpContext;
- }
- public IEnumerable<Template> GetTemplates()
- {
- // Get the full path of the View "Request"
- string requestViewPath = _httpContext.Request.MapPath(@"~/Views/Template/Templates");
- // Get all "cshtml" files from that folder
- string[] filePaths = Directory.GetFiles(requestViewPath, "*.cshtml");
- // For each files, get rid of the extension file
- return filePaths.Select(f => new Template() { Name = f.Split('\\').Last().Split('.').First() }).Where(t => string.Compare(t.Name, "_viewstart", true) != 0);
- }
- /// <summary>
- /// Convert a view to a string
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="viewName"></param>
- /// <param name="model"></param>
- /// <returns></returns>
- public string RenderViewToString<T>(ControllerContext controllerContext, string viewName, T model)
- {
- var view = ViewEngines.Engines.FindView(controllerContext, viewName, null).View;
- if (view != null)
- {
- var sb = new StringBuilder();
- using (var writer = new StringWriter(sb))
- {
- var viewContext = new ViewContext(controllerContext, view,
- new ViewDataDictionary(model), new TempDataDictionary(), writer);
- view.Render(viewContext, writer);
- writer.Flush();
- }
- return sb.ToString();
- }
- return string.Empty;
- }
- }
- }