C# HTML正在使用RazorEngine呈现为文本字符串。我怎样才能防止这种情况?
我正在尝试使用RazorEngine()生成一个HTML文档。一切都在正常工作,但我现在遇到的问题是一些HTML被正确呈现,而我嵌套在其中的HTML被呈现为文本HTML,因此浏览器显示的不是预期的表和div,而是例如C# HTML正在使用RazorEngine呈现为文本字符串。我怎样才能防止这种情况?,c#,razor,C#,Razor,我正在尝试使用RazorEngine()生成一个HTML文档。一切都在正常工作,但我现在遇到的问题是一些HTML被正确呈现,而我嵌套在其中的HTML被呈现为文本HTML,因此浏览器显示的不是预期的表和div,而是例如 "<table></table><div></div>" 然后将completeHTML写入文件 “InstallationTemplate.cshtml”定义为: @{ var installationReport =
"<table></table><div></div>"
然后将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>
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();
}
运行并返回renderedHtml
后,执行行返回到TemplateBase.cs
方法ITemplate.Run(ExecuteContext)
,该方法定义为:
@{
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>
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.cshtml
内容的转义HTML。例如:
如何使installationReport.DigiChannels()包含正确的HTML而不是当前正在执行的转义HTML?您是否尝试过:
@Raw(installationReport.DigiChannels())
编辑:我可以用以下方式使用它(MVC3)
@Raw
的替代方法是更改API以在适当的位置返回s
表示不应再次编码的HTML编码字符串
razor的默认行为是编码
string
s.不,我没有尝试过(甚至不知道!)。它工作得很好。谢谢我必须等几分钟才能将您的答案标记为正确。谢谢,是的,它与Html.Raw(在ASP.NET MVC中使用razor时)的功能基本相同
@Html.Raw(installationReport.DigiChannels())