In ASP.NET MVC, what is the advantage of using @RenderSection (versus say @RenderPage)?
I would like to be enlightened if I'm doing something wrong. I bet I am.
If I have the following code in my view page:
@{
ViewBag.Title = "About Us";
}
<h2>About</h2>
<p>
sample content.
</p>
@section header
{
<div id="header">
Chapter 3a: Creating a Consistent Look
</div>
}
...I should also have the ff in my layout page to render the section (if available) to prevent an exception at run-time:
@if (IsSectionDefined("header"))
{
@RenderSection("header")
}
However, if I don't have the last 4 lines above that checks for the section before rendering the section (say, I commented them all), the compiler will not check that I have a section defined in my view page, and allow me to build and run the application. During run-time, it is only then that I will get this error when I run the page:
The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_Layout2.cshtml": "header".
My questions then are the ff:
- How can we prevent this from happening? Is there any setting that forces the compiler to check for the missing
@RenderSection
code? - Doesn't the usage of the
@section
feature make a system less maintainable (assuming ques开发者_StackOverflow社区tion #1 has no positive answer) since we need to manually search for the presence of the@section
keyword throughout the entire application? - In this case, what is the advantage of using
@RenderSection
then as opposed to@RenderPage
? - Can we also make the
@section
conditional?
I've never thought of this as an issue. The concept is the same of placeholders in aspx syntax, so if you have 2 placeholders in your homepage, you're supposed to have 2 contents in each page/view using that masterpage.
There's a blog post of Phil Haack on the argument, it doesn't address your concerns directly but it's surely something interesting to consider.
http://haacked.com/archive/2011/03/05/defining-default-content-for-a-razor-layout-section.aspx
i know its old but if someone passed by this.
@RenderSection("header", required: false) by this you can either have a @section header { } in your view page or not.
And now you can also remove the check condition from your layout. also by this its conditional!
if you want it to be required you can : @RenderSection("header", required: true) but by this if your view doesn't have a @section header it will throw an error.
精彩评论