ASP.NET Web Pages - Page Layout
Creating a website with a consistent layout is easy with Web Pages.
Consistent Appearance
On the internet, you will find many websites with a consistent look and style:
- Each page has the same header
- Each page has the same footer
- Each page has the same style and layout
With Web Pages, you can achieve this efficiently. You can write reusable content blocks (like page headers and footers) in a single file.
You can also use layout templates (layout files) to define a consistent layout for all web pages on your site.
Content Blocks
Many websites have content that is displayed on every page of the site (like page headers and footers).
With Web Pages, you can use the @RenderPage() method to import content from different files.
Content blocks (from another file) can be imported anywhere on the web page. Content blocks can contain text, markup, and code, just like any ordinary web page.
Writing common headers and footers as separate files will save you a lot of work. You don't have to write the same content on every page, and when the content changes, you only need to modify the header or footer file to see the corresponding content updated on every page of the site.
Here's how it looks in the code:
Example
@RenderPage("header.cshtml")
@RenderPage("footer.cshtml")
Layout Page
In the previous section, you saw how easy it is to display the same content on multiple web pages.
Another way to create a consistent look is to use a layout page. A layout page contains the structure of the web page, not the content. When a web page (content page) links to a layout page, it will be displayed according to the structure of the layout page (template).
The layout page uses the @RenderBody() method to embed the content page, and it is no different from a normal web page otherwise.
Each content page must start with a layout directive.
Here's how it looks in the code:
Layout Page
@RenderBody()
Any Web Page
@{Layout="Layout.cshtml";}
D.R.Y. - Don't Repeat Yourself
With Content Blocks and Layout Pages, these ASP.NET tools allow your web application to display a consistent appearance.
These tools save you a lot of work, eliminating the need to repeat the same information on every page. Centralized markup, style, and code make your web application easier to manage and maintain.
Preventing File Browsing
In ASP.NET, files with names starting with an underscore can prevent these files from being browsed online.
If you don't want your content blocks or layout pages to be seen by your users, you can rename these files:
_header.cshtml
_footer.cshtml
_Layout.cshtml
Hiding Sensitive Information
In ASP.NET, the most common way to hide sensitive information (database passwords, email passwords, etc.) is to save this information in a separate file named "_AppStart".