Understanding shared layouts
Working with Layouts
Change views and layout pages
Try selecting the menu links MvcMovie, Home, and Privacy. Each page shows the same menu layout. The menu layout is implemented in the Views/Shared/_Layout.cshtml
file.
Open the Views/Shared/_Layout.cshtml
file.
Layout templates allow:
Specifying the HTML container layout of a site in one place.
Applying the HTML container layout across multiple pages in the site.
Find the @RenderBody()
line. RenderBody
is a placeholder where all the view-specific pages you create show up, wrapped in the layout page. For example, if you select the Privacy link, the Views/Home/Privacy.cshtml
view is rendered inside the RenderBody
method.
A shared layout is roughly comparable to a header template of a document where all pages show the same header!
Change the title, footer, and menu link in the layout file
Replace the content of the Views/Shared/_Layout.cshtml
file with the following markup.
Note: The changes are summarized after the code snippet
The preceding markup made the following changes:
Three occurrences of
MvcMovie
toMovie App
.The anchor element
<a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">MvcMovie</a>
to<a class="navbar-brand" asp-controller="Movies" asp-action="Index">Movie App</a>
.
In the preceding markup, the
asp-area=""
anchor Tag Helper attribute and attribute value was omitted because this app isn't using Areas.
Note: The Movies
controller hasn't been implemented. At this point, the Movie App
link isn't functional.
Save the changes and select the Privacy link. Notice how the title on the browser tab displays Privacy Policy - Movie App instead of Privacy Policy - MvcMovie
Select the Home link.
Notice that the title and anchor text display Movie App. The changes were made once in the layout template and all pages on the site reflect the new link text and new title.
How is the shared layout applied to all pages?
Examine the Views/_ViewStart.cshtml
file:
The Views/_ViewStart.cshtml
file brings in the Views/Shared/_Layout.cshtml
file to each view. The Layout
property can be used to set a different layout view, or set it to null
so no layout file will be used.
Last updated