Are there hooks in ASP.NET MVC prior to layout exe

2019-03-11 09:53发布

问题:

When ASP.NET MVC executes a page containing Razor it will first run the body eg the RenderBody method then it runs the code for the layout and weaves it together.

This is documented in this blog post:

System.Web.Mvc.RazorView.RenderView() System.Web.WebPages.WebPageBase.ExecutePageHierarchy() //non virtual version System.Web.WebPages.WebPageBase.PushContext()
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() //virtual version this.Execute() //Generated code from our View
System.Web.WebPages.WebPageBase.PopContext
RenderSurrounding(virtualPath, body); //Render Layout, which is similar to View's rendering process, essentially you can have nested Layout VerifyRenderdBodyOrSetions();

I want to add code to my views and layout that traces the actual logical position in the page.

Is there a way I can hook up a method to run just before RenderSurrounding and just after RenderBody finishes executing?

回答1:

You can override the ExecutePageHierarchy method on the page itself by creating a different base type for your pages, given a WebViewPage implementation like this:

public abstract class CustomViewPage<TModel> : WebViewPage<TModel>
{
    public override void ExecutePageHierarchy()
    {
        Output.Write("Before");
        base.ExecutePageHierarchy();
        Output.Write("After");
    }
}

You will get output just before and after the actual page's content (and thus inside the layout). I'm not sure if thats what you are looking for, are you trying to just write the scripts at </body> I imagine?

The main thing is to use this kind of a base type for just the main .cshtml (not any partials or on the layout) it will render those Output.Writes around the RenderBody output of the layout (well really, just inside).

You can set the base type per directory in the web.config.