Monday, June 3, 2013

Razor layout file sample and explanation

Take a look at a typical Razor layout file (_Layout.cshtml  or  _Layout.vbhtml):
<!DOCTYPE html>
        <html lang="en">
            <head>
                 <meta charset="utf-8" />
                 <title>@View.Title</title>
           </head>
        <body>
                  <div class="header">
                      @RenderSection("Header")
                 </div>
                        @RenderBody()
                <div class="footer">
                      @RenderSection("Footer")
                </div>
       </body>
       </html>


The layout file contains the main HTML content, defining the HTML structure for the entire site. The layout relies on variables (such as @View.Title) and special functions like @RenderSection([Section Name]) and @RenderBody() to interact with individual pages.
Once a Razor layout is defined, pages reference the layout and supply content for the sections defined within the layout. The following is a basic content page that refers to the previously defined _Layout.cshtml file:

@{ Layout = "~/_Layout.cshtml"; }
@section Header {
 <h1>My Blog<h1>
}
@section Footer {
 Copyright 2011
}
<div class="main">
 This is the main content.
</div>
rendered output (in HTML) shown in above figure 

1 - @view.title valued as my blog
2-  @RenderSection("header") as <h1>my blog</h1>
3 - @RenderBody as <div class="main"> This is the main content.</div>
4 - @RenderSection("Footer") as  Copyright 2011

No comments:

Post a Comment