Using Razor As Template System

When we think of rendering information, we often use a template system. In ASP.NET there are two built-in view engines, which are Razor and WebForm. We usually use the view engine to render view in MVC context.

However there are times that we need to render view files (.cshtml, .aspx) outside MVC lifecycle, such as rendering email content. Unfortunately we will need ControllerContext to do that .

So in this case, we can just use fake controller context and controller class itself to simulate view rendering process.

public class FakeController : Controller
{
}

public class RazorHelpers
{
   public static string GetRazorViewAsString(object model, string relativePath)
   {
       var st = new StringWriter();
       var context = new HttpContextWrapper(HttpContext.Current);
       var routeData = new RouteData();
       var controllerContext = new ControllerContext(new RequestContext(context, routeData), new FakeController());
       var razor = new RazorView(controllerContext, relativePath, null, false, null);
       razor.Render(new ViewContext(controllerContext, razor, new ViewDataDictionary(model), new TempDataDictionary(), st), st);
       return st.ToString();
   }
}

If you dont mind with additional dependency, you can just use RazorEngine library.