Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there hooks in ASP.NET MVC prior to layout execution and post body render?

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?

like image 499
Sam Saffron Avatar asked Feb 15 '12 23:02

Sam Saffron


People also ask

What is render body and render page in MVC?

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.

Can we have multiple RenderBody method in a view?

There can only be one RenderBody method per Layout page.

What are layouts in ASP NET MVC?

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.

What is the role of the layout file in an ASP NET MVC 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.


1 Answers

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.

like image 200
Paul Tyng Avatar answered Sep 17 '22 20:09

Paul Tyng