我试图用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>

其中InstallationReportDigiChannels定义如下:
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.cshtml内容的转义html。例如:
如何让@installationReport.DigiChannels()包含正确的html,而不是它当前正在执行的转义html?

最佳答案

你试过了吗:

@Raw(installationReport.DigiChannels())

编辑:我可以用以下方式使用它(MVC3)
@Html.Raw(installationReport.DigiChannels())

07-25 21:37