自定义WebViewPage注入code当剃刀模板渲染 [英] Custom WebViewPage inject code when razor template is rendering
本文介绍了自定义WebViewPage注入code当剃刀模板渲染的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个自定义的剃刀视图基类(继承 WebViewPage
),将每个视图模板注入一些HTML渲染(包括布局和局部查看)让我有每个刀片模板开始在客户端(在它结束没兴趣)上的参考。
我已经试过到目前为止
- 重写Write方法(如在评论描述这里) 。这将给code在每个刀片部分,不只是一次按模板(每次使用的HTML.TextBoxFor时间例子)
- 重写ExecutePageHierarchy方法(如上述的链路的交描述)。这每一个它击中的第一个
PopContext
通话时抛出一个错误:的RenderBody的方法还没有被调用的页面布局〜/查看/共享/_Layout.cshtml。
解决方案
想我回答这个现在:
公共抽象类CustomWebViewPage:WebViewPage
{
公众覆盖无效ExecutePageHierarchy()
{
VAR layoutReferenceMarkup = @<脚本类型=text / html的数据布局-ID =+ TemplateInfo.VirtualPath + @>< / SCRIPT>中;
base.ExecutePageHierarchy();
字符串输出= Output.ToString();
//如果身体标记为present脚本标记应注入,否则只是追加
如果(output.Contains(&所述; /体>中))
{
Response.Clear();
回复于(output.Replace(< /身体gt;中,layoutReferenceMarkup +< /身体GT;));
到Response.End();
}
其他
{
Output.Write(layoutReferenceMarkup);
}
}
}
公共抽象类CustomWebViewPage< TModel的计算值:CustomWebViewPage
{
}
似乎工作,但如果任何人有一个更好的解决方案,请分享。
I'm trying to create a custom Razor view base class (inheriting WebViewPage
) that will inject a bit of HTML for each view template being rendered (including Layouts and Partial Views) so that I have a reference on the client of where each Razor template starts (not interested in where it ends).
What I have tried so far is
- overriding the Write method (as described in a comment here) . This injects code at every razor section, not just once per template (for example every time that you use the HTML.TextBoxFor)
- overriding the ExecutePageHierarchy method (as described in the post of the link above). This throws an error every time it hits the first
PopContext
call:The "RenderBody" method has not been called for layout page "~/Views/Shared/_Layout.cshtml".
解决方案
Think that I have an answer to this now:
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
{
}
Seems to work, but if anyone has a better solution, please share.
这篇关于自定义WebViewPage注入code当剃刀模板渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文