Wednesday, March 2, 2011

[ASP.NET MVC]–Defining Multiple Layout Sections with Razor View Engine

When using MasterPages in ASP.NET web forms you can create a number of ‘ContentPlaceHolder’ sections that allow you to have various editable sections in your template. One example is that you may have something like:

 
<div id="contentBackgroundTop" class="contentBackground">
    <asp:ContentPlaceHolder ID="HeadingPlaceHolder" runat="server">
    </asp:ContentPlaceHolder>
</div>
<div id="contentBackgroundMiddle" class="contentBackground">
        <asp:ContentPlaceHolder ID="PagePlaceHolder" runat="server">
        </asp:ContentPlaceHolder>
</div>

Which lets you have a separate div for your page heading text, and then a div below it for the rest of your content. I recently started using Razor view engine in ASP.NET MVC and was interested in doing a similar thing, here’s how.

The Razor equivalent of master pages is a _Layout.cshtml file. which by default has a @RenderBody() call to do the rendering of your view. However I wanted to have another section to render different text, so I added the following to my layout:

<div id="contentBackgroundTop" class="contentBackground">
    @RenderSection("Heading", false)
</div>
<div id="contentBackgroundMiddle" class="contentBackground">
    @RenderBody()
</div>

As you can see, I’ve added a called to @RenderSection, which takes 2 parameters, the first being the name of the section, the second being a boolean as to whether it’s optional or not – this is very handy as ASP.NET Web Forms forces it to be compulsory.

For my Body content, my view stays the same, except I added the following code to render the Heading section:

@section Heading
{
    <h1>
       Heading Goes Here</h1>
}
This is a nice, neat syntax which you can just add to the top of your view.

No comments: