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?
RenderBody is used for rendering the content of the child view. In layout pages, it renders the portion of a content page. It takes the content of the child page and merges into the layout.
There can only be one RenderBody method per Layout page.
Razor has a feature called "layouts" that allow you to define a common site template, and then inherit its look and feel across all the views/pages on your web application.
The layout view allows you to define a common site template, which can be inherited in multiple views to provide a consistent look and feel in multiple pages of an application.
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.Write
s around the RenderBody
output of the layout (well really, just inside).
You can set the base type per directory in the web.config
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With