A layout page in ASP.NET Web Pages serves as a template for other web pages. It allows you to define a consistent structure and design for your web application, ensuring that common elements like headers, footers, and navigation menus are reused across multiple pages.

Benefits of Using a Layout Page

  • Consistency: Ensures a uniform look and feel across all pages.
  • Maintainability: Changes made to the layout page automatically reflect on all pages that use it.
  • Separation of Concerns: Keeps the layout and content separate, making it easier to manage both.

How to Create and Use a Layout Page

  1. Create a Layout Page: Create a new file named _Layout.cshtml in your project. This file will contain the common HTML structure for your web pages.
  2. Define the Layout Structure: In the _Layout.cshtml file, define the HTML structure, including placeholders for content.
  3. Use the Layout in Other Pages: In your individual web pages, specify that they should use the layout page by including the Layout directive.

Sample Code for a Layout Page

Below is an example of what your _Layout.cshtml file might look like:

        
<!DOCTYPE html>
<html>
<body>
<header>
<h1>My Website Header</h1>
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/About">About</a></li>
<li><a href="/Contact">Contact</a></li>
</ul>
</nav>
</header>
<main>
@RenderBody()
</main>
<footer>
<p>© 2023 My Website</p>
</footer>
</body>
</html>

Using the Layout in a Web Page

To use the layout page in another web page, such as Index.cshtml, you would include the following directive at the top of the file:

        
@{
Layout = "_Layout.cshtml";
}
<h2>Welcome to My Website!</h2>
<p>This is the home page content.</p>

Conclusion

Layout pages in ASP.NET Web Pages are a powerful feature that helps maintain a consistent design across your web application. By defining a layout page and using it in your individual web pages, you can streamline your development process and improve maintainability.