我正在尝试使用 RazorEngine ( http://razorengine.codeplex.com/ ) 生成 HTML 文档。一切大部分都在工作,但我现在遇到的问题是一些 HTML 被正确呈现,而我嵌套在其中的 HTML 被呈现为文字 HTML,而不是浏览器显示表格和 div 如预期的那样,它正在显示例如
"<table></table><div></div>"
我通过调用以下命令开始此过程:
string completeHTML = RazorEngine.Razor.Parse("InstallationTemplate.cshtml", new { Data = viewModels });
然后将 completeHTML
写入文件。
“InstallationTemplate.cshtml”定义为:
@{
var installationReport = new InstallationReport(Model.Data);
}
<!DOCTYPE html>
<html>
<head></head>
<body>
<div>
<!-- I would expect this to write the rendered HTML
in place of "@installationReport.DigiChannels()" -->
@installationReport.DigiChannels()
</div>
</body>
</html>
其中InstallationReport
和DigiChannels
定义如下:
public static class InstallationReportExtensions
{
public static string DigiChannels(this InstallationReport installationReport)
{
return installationReport.GetDigiChannelsHtml();
}
}
public class InstallationReport
{
public string GetDigiChannelsHtml()
{
// the following renders the template correctly
string renderedHtml = RazorReport.GetHtml("DigiChannels.cshtml", GetDigiChannelData());
return renderedHtml;
}
}
public static string GetHtml(string templateName, object data)
{
var templateString = GetTemplateString(templateName);
return RazorEngine.Razor.Parse(templateString, data);
}
在 GetDigiChannelsHtml()
运行并返回 renderedHtml
之后,执行行返回 TemplateBase.cs
到方法 ITemplate 中。 Run(ExecuteContext context)
,定义为:
string ITemplate.Run(ExecuteContext context)
{
_context = context;
var builder = new StringBuilder();
using (var writer = new StringWriter(builder))
{
_context.CurrentWriter = writer;
Execute(); // this is where my stuff gets called
_context.CurrentWriter = null;
}
if (Layout != null)
{
// Get the layout template.
var layout = ResolveLayout(Layout);
// Push the current body instance onto the stack for later execution.
var body = new TemplateWriter(tw => tw.Write(builder.ToString()));
context.PushBody(body);
return layout.Run(context);
}
return builder.ToString();
}
当我检查 builder.ToString()
时,我可以看到它包含用于 InstallationTemplate.cshtml
内容的正确 HTML,以及用于 DigiChannels 的转义 HTML。 cshtml
东西。例如:
如何让 @installationReport.DigiChannels()
包含正确的 HTML 而不是它当前正在执行的转义 HTML?
最佳答案
你试过吗:
@Raw(installationReport.DigiChannels())
编辑:我可以按以下方式使用它 (MVC3)
@Html.Raw(installationReport.DigiChannels())
关于c# - HTML 正在使用 RazorEngine 呈现为文字字符串。我怎样才能防止这种情况发生?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17835280/