解决方案是使用RazorEngine
例如:
public static string RenderPartialViewToString(string templatePath, string templateName, object viewModel)
{
string text = File.ReadAllText(Path.Combine(templatePath, templateName));
string renderedText = Razor.Parse(text, viewModel);
return renderedText;
}
在这种情况下,templateName是一个.cshtml包含以下 Html 和 Razor 代码的文件:
<div>
<h1>Age: @Model.Age</h1>
<input type="button" value="Just a Sample Button" />
</div>
并且viewModel只是一个匿名对象,定义为
var anonObj = new
{
Age = 10,
};
Razor.Parse()解析内容templateName并将内联 C# 替换为 HTML 中的值的神奇之处。