Skip to content

Instantly share code, notes, and snippets.

@sniffdk
Last active August 28, 2018 12:23
Show Gist options
  • Save sniffdk/6a8b0ff96439d1a17769 to your computer and use it in GitHub Desktop.
Save sniffdk/6a8b0ff96439d1a17769 to your computer and use it in GitHub Desktop.
Snippets showing how to render razor files with WebPages and MCV
public class RazorHelpers
{
// This approach is using WebPages, where there is no concept of a Controller
public static string RenderTemplate(string template, object model)
{
var page = WebPageBase.CreateInstanceFromVirtualPath("~/templates/" + template + ".cshtml");
var context = new WebPageContext(new HttpContextWrapper(HttpContext.Current), page, null);
var htmlWriter = new StringWriter();
// Access your model through PageData["Model"] in the view
context.PageData["Model"] = model;
page.ExecutePageHierarchy(context, htmlWriter);
return htmlWriter.ToString();
}
// Mvc approach using a fake controller context and a real model
public static string RenderTemplate(string template, object model)
{
using (var controller = new TempController {ViewData = {Model = model}})
{
var routeData = new RouteData();
// route data needs a controller entry with a non-empty string
routeData.Values.Add("controller", "temp");
var controllerContext = new ControllerContext(HttpContext.Current, routeData, controller);
var viewResult = ViewEngines.Engines.FindView(controllerContext, "~/Views/Partials/Templates/" + template + ".cshtml", null);
using (var writer = new StringWriter())
{
var viewContext = new ViewContext(controllerContext, viewResult.View, controller.ViewData, controller.TempData, writer);
viewResult.View.Render(viewContext, writer);
viewResult.ViewEngine.ReleaseView(controllerContext, viewResult.View);
return writer.ToString();
}
}
}
// Used for faking a controller context when rendering razor views to strings
private class TempController : Controller { }
}
@LiveHosting
Copy link

Hi. After so many hours of research, tons of nuget packages, razor engines and walls of code i finally found your super simple code snippet for rendering cshtml and vbhtml template files containing orders, invoices, etc. I'm using this to send emails, to generate pdf from html and so on.

Amazing snippet. Just what i needed so badly. Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment