渲染 razor 模板时自定义 WebViewPage 注入代码

hof*_*lie 3 .net c# asp.net asp.net-mvc razor

我正在尝试创建一个自定义 Razor 视图基类(继承WebViewPage),它将为正在渲染的每个视图模板(包括布局和部分视图)注入一些 HTML,以便我在客户端上有每个 Razor 模板开始位置的引用(对它结束的地方不感兴趣)。

到目前为止我尝试过的是

  1. 重写 Write 方法(如此处的注释中所述)。这会在每个 razor 部分注入代码,而不仅仅是每个模板一次(例如每次使用 HTML.TextBoxFor 时)
  2. 重写 ExecutePageHierarchy 方法(如上面链接的帖子中所述)。每次调用第一个调用时都会抛出错误PopContextThe "RenderBody" method has not been called for layout page "~/Views/Shared/_Layout.cshtml".

小智 5

在尝试您的解决方案后,我在使用部分视图的复杂页面的渲染 HTML 方面遇到了一些问题。

我的问题是一切都颠倒了。(部分视图顺序)

更正 - 我最终替换了 OutputStack 中的输出流

    public override void ExecutePageHierarchy()
    {

        // Replace output stream with a fake local stream
        StringWriter fakeOutput = new StringWriter();

        // Save output stack top level stream, and replace with fake local stream
        TextWriter outputStackTopOutput = OutputStack.Pop();
        OutputStack.Push(fakeOutput);

        // Run Razor view engine
        base.ExecutePageHierarchy();

        string content = fakeOutput.ToString();
        // Set back real outputs, and write to the real output 
        OutputStack.Pop();
        OutputStack.Push(outputStackTopOutput);
        outputStackTopOutput.Write(content);
    }
Run Code Online (Sandbox Code Playgroud)