Layout Views in ASP.Net MVC

Hi Friends,

Today, in this discussion we’ll talk about more on razor views. But, today we’ll dig inside layout views. What happens, Layouts basically use inherited methods to display content areas like

1)RenderBody and

so, layouts are basically similar to master pages what we have in web forms, it’s rather easy to understand. Methods like RenderBody or RenderSection will plugin the content views @ the specific page locations.

so, one obvious qn comes here, is how does mvc knows like how to use this layout view. and answer to this question which comes from _viewstart.cshtml which is there in the shared folder, here Layout property is getting set like below
so, whenever my view gets started, so prior to that this file runs and that is what the convention in razor view engine. so, basically this file resides in the root of the views folder, so before view runs basically this root runs, now let me go ahead and have multiple layouts for an application. is it possible. hmm yes.

so, what i need to do for this i just need to copy my viewstart and put inside one of the views sub folders and set the layout property with a different name.
Now, in order this to work we need to have that layout page defined in there. i can also have layout page set on the per view basis like
then it would look for that particular _Layout2 . I can also close the layout view just by saying

RenderSection is again a method which is going to inject content views @ one or more than one location, but this is optional.
it’s definition goes like
@RenderSection(“featured”,required:false) –> so, this means a content view can have section and cannot, but if i set to true the required field, then i must have section declared in the content page, otherwise it will result compiler error.

Now, let’s see how to decalare a section
@section featured
We are showing Latest Movie Reviews for all the Movies @Model.Count()
now, we can decalre this section any where on the page. Also, since we are on the home page, we could also go ahead and make option for my Movie Reviews, so that i can reach there from the home page itself like shown below.


Now, when i refresh the page i would get the below link on every page as shown below:-


With this i would like to wrap this section. In the next section we’ll see more about HTML Helpers, till then stay tuned and Happy Coding.

Happy Coding

Thanks, Rahul Happy Coding