Search code examples
c#asp.net-mvcrenderpartial

C# Render Partial View Without Controller


I am having trouble using "RenderPartialViewToString" without a controller class.

I am currently having to create HTML within application start up which requires making a model, making a view and turning the view in to a HTML string.

Within my view it uses HTML Helper function/extension which seems to only be there if a controller is there.

Can anyone shed some light on how I can do this?


Solution

  • Razor.Parse is deprecated now. With version 3.5 of the Razor engine you would follow the steps outlined here: https://antaris.github.io/RazorEngine/Upgrading.html

    The text below is copied verbatim from the above link:

    var result = Razor.Parse(razorTemplate, model, cache_name)
    

    is now either (when the modeltype is known or you want to precompile on startup)

    // Once at startup (not required when using an ITemplateManager which knows how to resolve cache_name)
    Engine.Razor.AddTemplate(cache_name, razorTemplate)
    // On startup
    Engine.Razor.Compile(cache_name, typeof(MyModel) /* or model.GetType() or null for 'dynamic'*/)
    
    // instead of the Razor.Parse call
    var result = Engine.Razor.Run(cache_name, typeof(MyModel) /* or model.GetType() or null for 'dynamic'*/, model)
    

    or (when you want lazy compilation, like Parse)

    // Once at startup (not required when using an ITemplateManager which knows how to resolve cache_name)
    Engine.Razor.AddTemplate(cache_name, razorTemplate)
    
    // instead of the Razor.Parse call
    var result = Engine.Razor.RunCompile(cache_name, typeof(MyModel) /* or model.GetType() or null for 'dynamic'*/, model)
    

    The semantic equivalent one-liner would be (only to be used to get started with RazorEngine quickly):

    // This will just call AddTemplate for you (every time), note that the ITemplateManager has to support AddTemplate
    // and it has to handle multiple calls to AddTemplate gracefully to make this work.
    // The default implementation will throw an exception when you use the same cache_name for different templates.
    var result = Engine.Razor.RunCompile(razorTemplate, cache_name, model.GetType() /* typeof(MyModel) or or null for 'dynamic'*/, model