Page Layout with Razor

Much of your page markup is common across views such as navigation, header, footer, general look and feel, and more. You want to write this markup once and use it everywhere. ASP.NET MVC provides _ViewStart.cshtml and _Layout.cshtml for this purpose. Note that the underscore used in the name of a page is a common way to indicate that the page is shared (and not accessed directly by a user).

The default _ViewStart.cshtml page sits inside the root of your Views folder in Solution Explorer. The ASP.NET runtime knows to look there to find a common layout for your pages. The following shows an example of the content in this page.

@{
  Layout = "_Layout.cshtml";
}

Notice that this default view start page simply points to the actual layout page, _Layout.cshtml, that is stored in the /Views/Shared directory. You might also define different view start pages inside your Views folders. This is helpful if a given set of views should render with a different layout. ASP.NET will look in your Views folders first; if not found, it will look for this default view start page. Note that you can also explicitly define your layout page at the top of a specific view.


Areas

You can further group your code inside what are called areas. These are useful when your site changes based on a specific area such as Shopping and Account. Inside this area, you would have folders for models, views, and controllers. You would likely use a separate _ViewStart.cshtml page as well to define the layout for the area.


The _Layout.cshtml page inside the Views/Shared folder works as the master layout page for your site. It includes your opening <html>, <head>, and <body> tags. It links to style sheets, loads any default JavaScript files, and defines your navigation. The layout page is then combined with a view at runtime to render a full set of HTML to the browser. We suggest that you open the page in Visual Studio and examine the markup.

The page uses the Razor call @RenderBody() to tell ASP.NET to embed the view in this exact section of the page. The following shows an example from within the markup for _Layout.cshtml with the integration of the current year.

<div class="container body-content">
  @RenderBody()
  <hr />
  <footer>
    <p>&copy; @DateTime.Now.Year - @AppSettings.Options.SiteTitle</p>
  </footer>
</div>

Similarly, there is another Razor call near the bottom of the layout: @RenderSection("scripts", required: false). This tells ASP.NET to render your scripts inside a section called "scripts". The following shows how you would use this in a view page. (will see an example of this in moment.)

@section Scripts {
  <script src="..."></script>
}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset