Modification of mao47's answer for latest razor syntax, this will also support partial views, and many other helper methods since it's getting Microsoft's helpers out of System.Web.Mvc.dll instead of just recreating some of their methods.
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Linq;
using System.Web.Hosting;
using System.Xml.Linq;
using RazorEngine.Configuration;
using RazorEngine.Templating;
public static class DynamicRazorTemplateParser
{
private static readonly IRazorEngineService service = RazorEngineService.Create(TemplateServiceConfiguration);
public static string RunCompile<T>(string template, string placeholder, T model, DynamicViewBag viewBag) where T : class
{
var templateSource = new LoadedTemplateSource(template);
return RunCompile(templateSource, placeholder, model, viewBag);
}
public static string RunCompile<T>(ITemplateSource template, string placeholder, T model, DynamicViewBag viewBag) where T : class
{
return service.RunCompile(template, placeholder, model.GetType(), model, viewBag);
}
public static string RunCompile(ITemplateSource template, string placeholder)
{
return service.RunCompile(template, placeholder);
}
private static TemplateServiceConfiguration TemplateServiceConfiguration
{
get
{
var config = new TemplateServiceConfiguration
{
BaseTemplateType = typeof(HtmlTemplateBase<>),
TemplateManager = new TemplateManager()
};
//TODO: Is this the best way?
var xDocument = XDocument.Load(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "/Views/Web.config");
if (xDocument.Root != null)
{
var sysWeb = xDocument.Root.Element("system.web.webPages.razor");
if (sysWeb == null) return config;
var pages = sysWeb.Element("pages");
if (pages != null)
{
var namespaces = pages.Element("namespaces");
if (namespaces != null)
{
var namespacesAdd = namespaces.Elements("add")
.Where(x => x.Attribute("namespace") != null)
.Select(x =>
x.Attribute("namespace").Value
);
foreach (var ns in namespacesAdd)
{
config.Namespaces.Add(ns);
}
}
}
}
return config;
}
}
private class TemplateManager : ITemplateManager
{
private readonly ConcurrentDictionary<ITemplateKey, ITemplateSource> _dynamicTemplates = new ConcurrentDictionary<ITemplateKey, ITemplateSource>();
private readonly string baseTemplatePath;
public TemplateManager()
{
baseTemplatePath = HostingEnvironment.MapPath("~/Views/");
}
public ITemplateSource Resolve(ITemplateKey key)
{
ITemplateSource templateSource;
if (this._dynamicTemplates.TryGetValue(key, out templateSource))
return templateSource;
string template = key.Name;
var ubuilder = new UriBuilder();
ubuilder.Path = template;
var newURL = ubuilder.Uri.LocalPath.TrimStart('/');
string path = Path.Combine(baseTemplatePath, string.Format("{0}", newURL));
string content = File.ReadAllText(path);
return new LoadedTemplateSource(content, path);
}
public ITemplateKey GetKey(string name, ResolveType resolveType, ITemplateKey context)
{
return new NameOnlyTemplateKey(name, resolveType, context);
}
public void AddDynamic(ITemplateKey key, ITemplateSource source)
{
this._dynamicTemplates.AddOrUpdate(key, source, (k, oldSource) =>
{
if (oldSource.Template != source.Template)
throw new InvalidOperationException("The same key was already used for another template!");
return source;
});
}
}
}
using System;
using System.IO;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using RazorEngine.Templating;
using RazorEngine.Text;
// ReSharper disable ClassWithVirtualMembersNeverInherited.Global
// ReSharper disable MemberCanBePrivate.Global
namespace Common.Core.Razor
{
[RequireNamespaces("System.Web.Mvc.Html")]
public class HtmlTemplateBase<T> : RazorEngine.Templating.HtmlTemplateBase<T>, IViewDataContainer
{
private HtmlHelper<T> helper;
private ViewDataDictionary viewdata;
private TempDataDictionary tempdata;
private AjaxHelper<T> ajaxHelper;
private ViewContext viewContext;
private UrlHelper urlHelper;
private readonly RequestContext _requestContext = HttpContext.Current.Request.RequestContext;
public UrlHelper Url => urlHelper ?? (urlHelper = new UrlHelper(_requestContext));
public ViewContext ViewContext
{
get
{
if (viewContext != null) return viewContext;
viewContext = GetViewContext();
return viewContext;
}
}
public AjaxHelper<T> Ajax
{
get
{
if (ajaxHelper != null) return ajaxHelper;
ajaxHelper = new AjaxHelper<T>(ViewContext, this);
return ajaxHelper;
}
}
public HtmlHelper<T> Html
{
get
{
if (helper != null) return helper;
helper = new HtmlHelper<T>(ViewContext, this);
return helper;
}
}
public ViewDataDictionary ViewData
{
get
{
if (viewdata == null)
{
viewdata = new ViewDataDictionary
{
TemplateInfo = new TemplateInfo() { HtmlFieldPrefix = string.Empty }
};
if (Model != null)
{
viewdata.Model = Model;
}
}
return viewdata;
}
set
{
viewdata = value;
}
}
public TempDataDictionary TempData
{
get { return tempdata ?? (tempdata = new TempDataDictionary()); }
set
{
tempdata = value;
}
}
public virtual string RenderView()
{
using (var writer = new StringWriter())
{
ViewContext.View.Render(ViewContext, CurrentWriter);
return writer.GetStringBuilder().ToString();
}
}
private ViewContext GetViewContext()
{
if (HttpContext.Current == null) throw new NotImplementedException();
var requestContext = _requestContext;
var controllerContext = ControllerContext(requestContext);
var view = GetView(requestContext, controllerContext);
//Can't check if string writer is closed, need to catch exception
try
{
var vContext = new ViewContext(controllerContext, view, ViewData, TempData, CurrentWriter);
return vContext;
}
catch
{
using (var sw = new StringWriter())
{
var vContext = new ViewContext(controllerContext, view, ViewData, TempData, sw);
return vContext;
}
}
}
private IView GetView(RequestContext requestContext, ControllerContext controllerContext)
{
if ((string)requestContext.RouteData.DataTokens["Action"] != null)
{
requestContext.RouteData.Values["action"] = (string)requestContext.RouteData.DataTokens["Action"];
}
var action = requestContext.RouteData.GetRequiredString("action");
var viewEngineResult = ViewEngines.Engines.FindPartialView(controllerContext, action);
if (viewEngineResult != null && viewEngineResult.View != null)
{
return viewEngineResult.View;
}
viewEngineResult = ViewEngines.Engines.FindView(controllerContext, action, null);
if (viewEngineResult == null)
{
throw new Exception("No PartialView assigned in route");
}
return viewEngineResult.View;
}
public void SetView(string view)
{
_requestContext.RouteData.DataTokens["Action"] = view;
}
private ControllerContext ControllerContext(RequestContext requestContext)
{
ControllerBase controllerBase;
var routeDataValue = "EmptyController";
if (requestContext.RouteData.Values["controller"] != null && (string)requestContext.RouteData.Values["controller"] != routeDataValue)
{
var controllerName = (string)requestContext.RouteData.Values["controller"];
IController controller = ControllerBuilder.Current.GetControllerFactory().CreateController(requestContext, controllerName);
controllerBase = controller as ControllerBase;
}
else
{
var controller = new EmptyController();
controllerBase = controller; //ControllerBase implements IController which this returns
requestContext.RouteData.Values["controller"] = routeDataValue;
}
var controllerContext =
new ControllerContext(requestContext.HttpContext, requestContext.RouteData, controllerBase);
return controllerContext;
}
private class EmptyController : Controller { }
public override void WriteTo(TextWriter writer, object value)
{
if (writer == null)
throw new ArgumentNullException("writer");
if (value == null) return;
//try to cast to RazorEngine IEncodedString
var encodedString = value as IEncodedString;
if (encodedString != null)
{
writer.Write(encodedString);
}
else
{
//try to cast to IHtmlString (Could be returned by Mvc Html helper methods)
var htmlString = value as IHtmlString;
if (htmlString != null) writer.Write(htmlString.ToHtmlString());
else
{
//default implementation is to convert to RazorEngine encoded string
base.WriteTo(writer, value);
}
}
}
}
}