WebPages Layout
Layouts in ASP.NET WebPages provide a way to create consistent designs for your web application. They allow you to define reusable sections like headers, footers, and navigation menus, ensuring a uniform look across multiple pages.
Key Topics
What is a Layout?
A layout is a master template for your web application. It defines shared sections of your website, such as headers and footers, so you don't have to duplicate HTML across multiple pages.
Creating a Layout Page
Example
<!DOCTYPE html>
<html>
<head>
<title>@Page.Title</title>
<link rel="stylesheet" href="/styles/site.css" />
</head>
<body>
<header>
<h1>My Website</h1>
<nav>
<a href="/">Home</a>
<a href="/about">About</a>
</nav>
</header>
<main>
@RenderBody()
</main>
<footer>
<p>Copyright © 2024</p>
</footer>
</body>
</html>
Output
A page with a consistent header, footer, and navigation links.
Explanation: This layout page includes placeholders like @RenderBody()
, which will render the unique content of individual pages.
Using a Layout in a Page
Example
@{
Layout = "_Layout.cshtml";
}
<h2>Welcome to My Website</h2>
<p>This is the homepage.</p>
Output
The homepage content will be rendered within the layout's main section.
Explanation: The Layout
variable specifies which layout file to use for the page. Unique content (e.g., the homepage text) is rendered in the @RenderBody()
section of the layout.
Key Takeaways
- Layouts simplify maintenance by centralizing common HTML structures.
- Use
@RenderBody()
to define where page-specific content will appear. - Layouts promote a consistent design across your application.