简体   繁体   中英

Does ASP.NET MVC 3 Razor output buffer views?

In ASP.NET MVC 3 Razor, you can specify the page title with:

@{
    ViewBag.Title = "Title";
}

Now, suppose we have a layout page with:

<title>@ViewBag.Title | Website</title>

When ASP goes to render a page, it will need to output some of the layout page HTML, then the view HTML, then the rest of the layout page HTML.

In order to output the first half of the layout page HTML, ASP.NET will need to know the value given to ViewBag.title in the view. Thus, ASP.NET needs to parse the Razor code in the view. However, ASP.NET can't output the view's HTML code just yet because it is still outputting the layout page's HTML code. So does ASP.NET store the HTML output of the view in a buffer? That seems like a bad practice, but I can't think of any other way to efficiently get the view's title into the layout page output.

When ASP goes to render a page, it will need to output some of the layout page HTML, then the view HTML, then the rest of the layout page HTML.

That's how web forms are rendered. However due to the issue you describe (along with a few others) mvc renders inside out.

So the inner view is rendered first to a temporary buffer. Then the layout page. This rendering continues until the outer most layout page is reached when the buffer is then wrote to the response stream and flushed.

This doesn't cause any issues 90% of the time (guestimate) however this will cause headaches if you ever need to flush the response early.

FYI the buffer for the views can be accessed with:

HtmlHelper.ViewContext.Writer

So to answer your question, yes - it does buffer views.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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