Generally a web page contains several different parts. For example,
Header content, Navigation pane, Common page layout items, Common page markups
(CSS, Scripts), etc. So these parts should be managed properly. All of these
parts should not be loaded always and should behave separately. To handle these
burdens, we should manage a proper structure for the page.
In ASP.NET web forms, you can do this using master pages, content pages, user controls, place holders and likewise. But with ASP.NET MVC 3 and Razor View Engine, you can achieve more complex structures and behaviors than web forms. Razor View Engine is the power of ASP.NET MVC 3 and its API lies on top of ASP.NET API. This API gives us all the facilities to maintain the structure of the page.
(image source : www.asp.net)
I’ll explain step by step, how to
make a structure for your ASP.NET web page.
01). in the default MVC 3 project, you can see a folder “~/Views/Shared”. This folder is the place for the content that is shared among all controllers.
It contains a file called “_Layout.cshtml”.
(Note: As a practice, we put ‘_’ before
the file name, if it is definitely used with some other View)
This file is the Master page for all
the views. You can add all unaltered content of your site like Search bar,
Navigation Pane, Script and CSS links (Common Page Markups) into this file.
How is this set as the master page?
Here you can see a code line in this
file as “@RenderBody()”. This line allocates a space to render a View into this
page. Then you should set the layout on top of your View as,
@{
Layout
= "~/Views/Shared/_Layout.cshtml";
}
But this is not required to do in all
View files. You can do it in ViewStart.cshtml file, as you see in default MVC 3
project. Because web servers go through ViewStart file, for all web requests,
before it goes to any other View file. Only when you use different Layout, you can
set it in particular View file.
02). There is another Razor method called “RenderSection()”. It gives more control on rendering. There you can specify a part of the View file that should be rendered in one place.
This false value says that the section is not “required”.
Unless it gives an Error Message saying “the section is not declared”.
03). if you want to render the content of another View file
into the file that you are working in, you can use “RenderPartial(<file name>)”
method.
It doesn’t need more work. You can just type
@RenderPartial(<file name>), and it will render the whole content into
the file.
I think using these methods; you can create any complex
structure for your Web Site.


