Saturday, May 12, 2012

ASP.Net MVC: Layout Page

Layout page is a Razor page that is common to multiple pages. Shared "shell" page used by other pages.

  • Lives in /Views/Shared
  • By convention named, _layout.cshtml
  • How does MVC know how to use this view? _ViewStart.cshtml
  • Contains the normal html tags such as html, head, and body. Layout page sets the title of the page using ViewBag.Title value
  • @RenderBody(), that appears under the body tag of the layout page, is the placeholder where view-specific pages show up, surrounded by what is in the layout page
  • @RenderBody and @RenderSection allows plugging in of Content views
  • ViewBag is one way to pass data between your page and the layout page

Can set the Layout View at the top of the page
@{
   Layout  = “~/Views/Shared/_Layout.cshtml”
  // if not specified, rely on the _ViewStart.cshtml file in specific 
  // View directory or in the root of Views   directory
}

Layout page

  @RenderSection(“Footer”, true);  // true means required
  // To render View into another part of the layout

View page

  // If required, must specify in the View:
   @section Footer (Can be placed anywhere)
  {
    <p>This is the footer</p>
  }