【问题标题】:Rendering Razor partials as html将 Razor 部分渲染为 html
【发布时间】:2017-09-19 21:26:21
【问题描述】:
正如文章Unit test with Razor Generator 所述,我们可以对视图进行单元测试(在某种程度上)。问题是它说它忽略了部分代码,它们是真正独立的代码片段,非常适合单元测试。
如何将 .cshtml 文件(如 Html.RenderPartial(filePath, model))中使用的部分渲染为 html?所以我可以模拟模型并断言生成的 html。
【问题讨论】:
标签:
c#
asp.net-mvc
unit-testing
razor
view
【解决方案1】:
您可以使用独立的 RazorViewEngine found here. 来完成此操作,这将让您传入一个 ViewModel 并编译部分内容,然后返回一个 html 字符串。
然后,您可以使用来自另一个答案 found here* 的代码来编译部分。
*
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;
}
}