ASP.NET MVC 4 RenderSection
Today, i try to understand the ASP.NET MVC 4 RenderSection .
From msdn, there is no sample for me to have a quick understand on the usage.
How to use @RenderSection in practical?
When create a new MVC project, by default this line will appear at the bottom of your _Layout.chtml page.
@RenderSection("scripts", required: false )
Base on the new MVC project I change the 2nd parameter to try. So now the code look like this
@RenderSection("scripts", required: true )
and in the index.chtml I’ve added this code at the beginning of page
and the rest remain unchanged. In summary, it will now look like image below
So now if we would like to view the index.chtml it will look like below.
So now if we would like to view the contact.chtml you will hit error and complained Section not defined: “scripts”.
This is because the contact page does not have “@section scripts”, So when 2nd parameter had set to “true” even the view does not need to display anything in script section we still need to define it in the view
Alternatively, we can change code in the _Layout.chtml to look like below, so when now browse the view contact.chtml it will not throw error.