Jp_
Jp_

Reputation: 6193

Rendering Razor partials as html

As the article Unit test with Razor Generator states, we can unit test views (at some level). The problem is that it says that it ignores the partials, that are pieces of code really self contained, good for unit test.

How can I render as html a partial being used in a .cshtml file like Html.RenderPartial(filePath, model)? So I could mock the model and assert the html generated.

Upvotes: 0

Views: 186

Answers (1)

Stephen Vernyi
Stephen Vernyi

Reputation: 798

You can accomplish this with the standalone RazorViewEngine, found here. This will let you pass in a ViewModel and compile the partial, and spits back out an html string.

You can then use the code from another answer found here* to compile the partial.

*

public class RazorEngineRender {
    public static string RenderPartialViewToString<T>(string templatePath, string viewName, T model) {            
        string text = System.IO.File.ReadAllText(Path.Combine(templatePath, viewName));
        string renderedText = Razor.Parse(text, model);
        return renderedText;
}

}

Upvotes: 1

Related Questions