ASP.NET MVC 3 Razor Syntax - RenderBody, RenderPage and RenderSection

Posted by: Malcolm Sheridan , on 1/14/2011, in Category ASP.NET MVC
Views: 360103
Abstract: The following article demonstrates how to use these three method of Razor syntax -RenderBody, RenderPage and RenderSection in ASP.NET MVC 3.

Everybody knows Razor is the new view engine ASP.NET Web Pages, so I thought I’d write about some Razor syntax you may not be aware of. The three methods I’ll be focusing on today are RenderBody, RenderPage and RenderSection. You’ll need to understand how each of these work if you want to get know the Razor syntax intimately. This code also works in WebMatrix if you're using it.

Before moving on, you need to download ASP.NET MVC 3. Click here to download and install them using the Microsoft Web Platform Installer.

Open studio 2010 and create a new ASP.NET MVC 3 Web Application (Razor) project. Now it's time to start coding! I’ll begin with the RenderBody method.

RenderBody

The RenderBody method resides in the master page, or in Razor this is commonly referred to as the Layout page. There can only be one RenderBody method per Layout page. If you’re from Web Forms world, the easiest way to think of RenderBody is it’s like the ContentPlaceHolder server control. The RenderBody method indicates where view templates that are based on this master layout file should “fill in” the body content.

Render Body Razor MVC

RenderPage

Layout pages can also contain content that can be filled by other pages on disk. This is achieved by using the RenderPage method. This method takes either one or two parameters. The first is the physical location of the file, the second is an optional array of objects that can be passed into the page. Add a new cshtml file to the Shared folder and call it _Header.cshtml. I've prefixed this file with an underscore because I don't want this file to be called outside of RenderPage. By default, ASP.NET will not serve pages beginning with an underscore. Here's the code I'm adding to the _Header.cshtml page.

<h1>Header Here</h1>

And to use this in the layout, it's as easy as this.

Renderpage razor method

RenderSection

Layout pages also have the concept of sections. A layout page can only contain one RenderBody method, but can have multiple sections. To create a section you use the RenderSection method. The difference between RenderSection and RenderPage is RenderPage reads the content from a file, whereas RenderSection runs code blocks you define in your content pages. The following code illustrates how to render a footer section.

RenderSection razor method

RenderSection expects one parameter and that is the name of the section. If you don’t provide that, an exception will be thrown. Views can add data to sections by using the following code.

Rendersection views

If you ran the website now it’ll run without error. If on the other hand you don’t include the section footer in the view, you’ll get an error.

RenderSection exception

That’s because by default, sections are mandatory. To make sections optional, just add the second parameter, which is a Boolean value.

RazorSection optional

Now things will run just fine.

These three methods you will use time and time again when you're using the Razor view engine. This code works both for ASP.NET MVC 3 and also WebMatrix. Have fun!

The entire source code of this article can be downloaded over here

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Malcolm Sheridan is a Microsoft awarded MVP in ASP.NET, a Telerik Insider and a regular presenter at conferences and user groups throughout Australia and New Zealand. Being an ASP.NET guy, his focus is on web technologies and has been for the past 10 years. He loves working with ASP.NET MVC these days and also loves getting his hands dirty with jQuery and JavaScript. He also writes technical articles on ASP.NET for SitePoint and other various websites. Follow him on twitter @malcolmsheridan


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by stacey on Monday, January 17, 2011 8:58 AM
Cool! How do I write a server side comment in razor?
Comment posted by Malcolm Sheridan on Wednesday, January 19, 2011 12:07 AM
@stacey

@*  A one-line code comment. *@

@*
    This is a multiline code comment.
    It can continue for any number of lines.
*@  
Comment posted by Jarrod on Wednesday, March 16, 2011 4:47 PM
Nice short & very sweet explanation, helped me a great deal, thanks!
Comment posted by Carlito Justino on Saturday, April 23, 2011 6:51 PM
Thanks for the article, will be of great value to me
Comment posted by fsf on Friday, March 23, 2012 2:51 AM
c
Comment posted by jeff00seattle on Wednesday, May 9, 2012 6:37 PM
I have strange problem that is related to this article.

I have a Partial that I know that it is getting called and validated that it is receiving expected ViewData, but it does not always render.

Here is the partial:
@using WebUI.Domain.Digital
@if (null != ViewData["SelectedRow"])
{
    CardDigital cardDigital = (CardDigital)ViewData["SelectedRow"];
    string location = (string)ViewData["Location"];

    <fieldset>
        <legend>Digital Card (@location)</legend>
        <div class="display-label">
            FirstName</div>
        <div class="display-field">
            @cardDigital.FirstName
        </div>
        <div class="display-label">
            LastName</div>
        <div class="display-field">
            @cardDigital.LastName
        </div>
    </fieldset>
}
And here is the View code calling the Partial:
<div>
        <div>
...
           @if (grid.HasSelection)
                {
                        ViewData["SelectedRow"] = new CardDigital((CardDigital)grid.SelectedRow.Value);
                        ViewData["Location"] = "A";
                }
                @Html.Partial("Partial/_DigitalPreview");
        </div>
</div>
<div>
        @{ ViewData["Location"] = "B"; }
        @Html.Partial("Partial/_DigitalPreview")
</div>
Notice that there are two locations "A" and "B". Both @Html.Partial receive the same ViewData["SelectedRow"], but only Location "A" is rendering. I validated that @Html.Partial at Location "B" is getting the data, but it just is not presenting it.

What could be the issue?

Thanks
Comment posted by Malcolm Sheridan on Thursday, May 10, 2012 6:50 AM
@jeff00seattle

It doesn't always render? What are the scenarios when it does and doesn't?
Comment posted by gialang on Thursday, July 26, 2012 9:33 AM
Thanks You !
Comment posted by gialang on Thursday, July 26, 2012 9:37 AM
In _Header.cshtml, I use @RenderSection("name", false)
<br>
this error: [ The file "~/Views/Shared/_Header.cshtml" cannot be requested directly because it calls the "RenderSection" method] happened.
<br> Would you explained me about this. Thanks you !
Comment posted by Bilal on Friday, July 27, 2012 4:51 AM
Very good and clean explanation.. Saved me hours.. Thanks very much.
Comment posted by Israel on Wednesday, August 29, 2012 2:34 AM
I have problem with @RenderPage with custom HtmlHelper in same page.
When the @RenderPage is before the custom HtmlHelper the page looks OK.
When the custom HtmlHelper is before the @RenderPage, the HtmlHelper is not working.
Anyone encounter this problem?
Comment posted by Israel on Wednesday, August 29, 2012 2:37 AM
Regarding my previous comment, it is the opposite:

When the @RenderPage is before the custom HtmlHelper the HtmlHelper is not working (rendered).
When the custom HtmlHelper is before the @RenderPage, the HtmlHelper is working fine.
Thanks
Comment posted by GarageTechUser on Wednesday, November 7, 2012 12:57 AM
Very Nice..... Simple! Short!.. But Covers prety much every thing!!

Helped me a great deal, As Well................thanks!
Comment posted by Trekmac Tshepo on Sunday, January 26, 2014 3:59 AM
Thank you, very nice article

Im have a bit of a problem, I have posted the @RenderSection("sidebar", false) on the layout page, but the content only appear only on the Home/Index, all the other pages, there is no content appearing for the other pages
Comment posted by Venkat Dandu on Saturday, March 1, 2014 3:08 PM
@Trekmac Tshepo,

Did you included the "sidebar" section in all other view templates?
Comment posted by Venkat Dandu on Saturday, March 1, 2014 3:11 PM
@Trekmac Tshepo,

Did you included the "sidebar" section in all other view templates?