繁体   English   中英

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

[英]Custom WebViewPage inject code when razor template is rendering

我正在尝试创建一个自定义Razor视图基类(继承WebViewPage ),该基类将为正在渲染的每个视图模板(包括Layouts和Partial Views)注入一点HTML,以便在客户端上获得每个Razor模板位置的引用开始(对结束不感兴趣)。

到目前为止,我尝试过的是

  1. 重写Write方法(如在注释中所描述这里 )。 这会在每个剃刀区域注入代码,而不仅仅是每个模板注入一次(例如,每次使用HTML.TextBoxFor时)
  2. 重写ExecutePageHierarchy方法(如上面链接的文章中所述)。 每次PopContext第一个PopContext调用都会引发错误: The "RenderBody" method has not been called for layout page "~/Views/Shared/_Layout.cshtml".

在尝试完您的解决方案后,我对带有部分视图的复杂页面的呈现HTML遇到了一些问题。

我的问题是一切都被扭转了。 (部分视图的顺序)

纠正-我最终替换了OutputStack中的Output流

    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);
    }

认为我现在对此有一个答案:

public abstract class CustomWebViewPage: WebViewPage
{
    public override void ExecutePageHierarchy()
    {
        var layoutReferenceMarkup = @"<script type=""text/html"" data-layout-id=""" + TemplateInfo.VirtualPath + @"""></script>";

        base.ExecutePageHierarchy();
        string output = Output.ToString();

        //if the body tag is present the script tag should be injected into it, otherwise simply append
        if (output.Contains("</body>"))
        {
            Response.Clear();
            Response.Write(output.Replace("</body>", layoutReferenceMarkup+"</body>"));
            Response.End();
        }
        else
        {
            Output.Write(layoutReferenceMarkup);
        }
    }
}

public abstract class CustomWebViewPage<TModel>: CustomWebViewPage
{
}

似乎可以工作,但是如果有人有更好的解决方案,请分享。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM