Join Jess Chadwick for an in-depth discussion in this video Reusing shared markup with layouts, part of ASP.NET Core: Razor Pages.
- [Instructor] So far, I've created two pages in my application, and I've done so by copying and pasting all of the markup, including the site header, footer, and links to the CSS, etc., in order to keep a consistent look and feel throughout the site. That may be fine with two pages now, however, as I continue to add pages to this application, it will become really painful to change each instance of those common elements across all pages in the site when I need to do so.
Luckily, Razor pages allows us to define special pages whose sole purpose is to define a set of markup that will act as a common layout and render content from individual pages inside this layout. To demonstrate how they work, I'll start by making yet another copy of the Index.cshtml page, and rename it to _Layout.cshtml. It's important to point out that there's nothing special about the underscore or the name Layout in this file name.
Those are just naming standards that a lot of people use to indicate that this file is a layout and not a full page. However, this name will be important in just a minute as I reference it from my views. Once I've got the file copied, the first thing I'll do is remove all the Razor code up at the top, including the page directive, since this is no longer a Razor page. Then I'll find a place in the markup where I want the contents of pages to be rendered, like the container div on line 43, and I'll remove all of the content in that container.
Then I'll replace those contents with a call to a Razor function named RenderBody, which tells Razor to execute the page that's using this layout, then dump the resulting markup from that page at this point in the layout. With the layout in place, I can update each page to take advantage of this shared markup, by simply setting the value of their layout property to the name of the new layout file, without the extension.
With this line in place, I can then remove everything but the main section of content in these views.
Now, when we refresh the page again, it looks exactly the same, only this time, the main content is getting rendered by the Index view, and the layout of the page is getting rendered from the Layout view. Now, whenever I need to make a change to the layout, I can make it in one place and have it take effect across every page all at once.
- Creating a new application
- Setting up pages
- Rendering dynamic content
- Reusing markup with layouts
- Increasing the maintainability of pages
- Processing data
- Validating input
- Securing an application