MVC3 Razor @RenderSection

Source: Internet
Author: User

MVC3 's Razor View engine also provides @rendersection

My understanding: @RenderSection occupy a single digit in the master page, and then let the child pages that use this master page render their section themselves.

Define @rendersection ("section name") in master page _layout.cshtml

<body>
<div id= "header" >@{html.renderaction ("menu", "Global");} </div>
<div id= "SideBar" >
@RenderSection ("submenu")
</div>
<div id= "Container" > @RenderBody () </div>
<div id= "Footer" >@{html.renderaction ("Footer", "Global");} </div>
</body>

Add a about.cshtml, use _layout.cshtml to make a master page

You can then define what "submenu" is going to render in about.cshtml

@{
Viewbag.title = "about";
}

@section submenu{
Hello This is a section implement on about View.
}

Here I implemented the submenu in about.cshtml, running the result

But when a page that uses _layout.cshtml as the master page does not implement section,

For example, my new index.cshtml does not implement @section submenu{...}, it throws an exception

This is because I am using @rendersection ("submenu") in _layout.cshtml, and he requires all the children to be implemented,

You can use one of its other overloaded @rendersection ("submenu", false), and the second parameter indicates that it is not required, so it does not throw an exception.

Also, when I define @rendersection ("submenu", false) in the master page, I want to not implement this section when all the sub-pages are

, the master page can have its own rendered content, which can be used

<div id= "SideBar" >
@if (issectiondefined ("submenu"))
{
@RenderSection ("submenu", false)
}
Else
{
<p>submenu section was not defined!</p>
}
</div>

This will display the defined content by default when no page renders the section.

MVC3 Razor @RenderSection

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.