htmlvisual-studio-2010razorrazorgenerator

Is there an example on using Razor to generate a static HTML page?


I want to generate a static HTML page by RAZOR, basically by using includes of partial sub pages.

  1. I have tried T4 as well and do look for an alternative: see here and here
  2. This answer says it is possible - but no concrete example
  3. I have installed Razor generator because I thought this is the way to go, but I do not get how to generate static HTML with this.

Best would be a complete extension which behaves like the T4 concept, but allows me to use the RAZOR syntax and HTML formatting (the formatting issue is basically the reasons why I am not using T4).


Solution

  • If you are trying to take a Razor view and compile it and generate the HTML then you can use something like this.

    public static string RenderViewToString(string viewPath, object model, ControllerContext context)
    {
        var viewEngineResult = ViewEngines.Engines.FindView(context, viewPath, null);
        var view = viewEngineResult.View;
    
    
        context.Controller.ViewData.Model = model;
    
        string result = String.Empty;
        using (var sw = new StringWriter())
        {
    
            var ctx = new ViewContext(context, view,
                                      context.Controller.ViewData,
                                      context.Controller.TempData,
                                      sw);
            view.Render(ctx, sw);
    
            result = sw.ToString();
        }
    
        return result;
    }
    

    Or outside of ControllerContext http://razorengine.codeplex.com/