What's the point of using @RenderBody in a MVC

2019-06-15 13:37发布

问题:

In my MVC4 razor layout I am using @RenderSection and I don't bother with @RenderBody.

Then in the views I just place everything in sections.

This makes me wonder what's the point of @RenderBody other than to make it easier for people who don't want to put things in sections. Is there anything different from @RenderBody and something inside a @RenderSection?

回答1:

@RenderBody renders the content of your page that is not within any named sections. If all of your content is within one of your defined sections, there is no point. However...

In Razor syntax, @RenderSection replaces master pages. It allows you to carve out sections of the page for particular areas, and then allow the main body of the content to emerge naturally wherever the @RenderBody declaration is placed.

Let's say you are writing an invoice. The RenderBody area would the that part of the page that contains your invoice line items. This is true of most reports; there's always a header section, a body section and a footer section.

Presumably, rendering a section in the appropriate area of a web page allows you to obtain proper semantic behavior, such as styling the footer in a way that it always appears at the bottom of a page.

<footer>
  @RenderSection("Footer", @<span>This is my footer!</span>)
</footer>

http://msdn.microsoft.com/en-us/vs2010trainingcourse_aspnetmvc3razor_topic2.aspx

http://haacked.com/archive/2011/03/05/defining-default-content-for-a-razor-layout-section.aspx