Webpages Layout in ASP
Great! Here’s a clear and practical introduction to Layouts in ASP.NET Web Pages (Razor) — how they work, why they’re useful, and how to use them.
ASP.NET Web Pages – Layouts
? What Is a Layout?
A Layout is a shared template (like a master page) that defines the common structure of your website — e.g., header, footer, navigation.
You define it once in a _Layout.cshtml file, then reuse it across multiple pages to maintain a consistent design.
? Typical File Structure
/Site |_ _Layout.cshtml |_ Index.cshtml |_ About.cshtml? Example: _Layout.cshtml
<!DOCTYPE html><html><head> <title>@Page.Title</title> <link rel="stylesheet" href="/styles.css" /></head><body> <header> <h1>My Website</h1> <nav> <a href="/">Home</a> | <a href="/About">About</a> </nav> </header> <main> @RenderBody() <!-- This is where page-specific content goes --> </main> <footer> <p>© @DateTime.Now.Year</p> </footer></body></html>? Example: A Page Using the Layout (e.g., Index.cshtml)
@{ Layout = "_Layout.cshtml"; Page.Title = "Welcome";}<h2>Welcome to my site</h2><p>This content is coming from Index.cshtml.</p>? How It Works
@RenderBody()in_Layout.cshtmlis replaced with the content ofIndex.cshtml,About.cshtml, etc.Layout = "_Layout.cshtml"tells the page to use the layout.Page.Titlesets the<title>dynamically.
? Optional: Sections
To define optional content like custom scripts per page:
In Layout:
@RenderSection("Scripts", required: false)In Page:
@section Scripts { <script>alert("Page-specific JS");</script>}? Benefits of Using Layouts
Consistency across pages
Cleaner code (don’t repeat headers/footers/navigation)
Easier updates (change layout in one place)
Let me know if you want a working example with routing, partial views, or combining layout with database output!