Computer Magic Logo
Sections

Wednesday, June 24, 2015

Published by Aristotelis Pitaridis

We saw that we can define the location in the Master Template that we want to add contents that each page will be able to display dynamic data. There are a lot of cases that we want to have more than one part of the page to be dynamic inside a Master Template. In order to add more dynamic parts in a page we can use the Sections.

Before we add sections in our Master Template, let’s create a header and a footer so that we will be able to demonstrate how to use the sections.

In order to define a Section we will replace the Header’s text with the Section command.

With the @RenderSection("Header") command the ASP.NET MVC framework to ask from the template which uses the Master Template to generate some HTML which will have the name Header. If we try now to see the home page we will see that the Section not defined: "Header" error message will appear on the screen. This happens because we defined the place that the section has to be placed but we did not declare it in the HomePage template. Let’s add the extra code required in the HomePage template in order to fix this problem. We open the HomePage template and add the definition of the Header section.

If we try to see the home page again we will see that now it works and the header appears on the screen. This works fine but how can we define a section which will not be mandatory for the template to generate contents. This happens a lot of times when we create web pages and this can be resolved very easily by using the second Boolean parameter which defines if the section is required. We edit the Master Template and we replace the Footer static text with a section which is not required to be defined by the template.

If we try to see the homepage we will see that it works as it is supposed to work. The footer text will be removed because we replaced it with a section and we have not defined it in the HomePage template. Let’s add some text in the Footer by editing the HomePage template.