Please describe to me how we will create a layout view in Razor view engine with an example.
How to create layout View in Asp.Net MVC Razor View
868
07-Feb-2020
Updated on 07-Feb-2020
Nishi Tiwari
07-Feb-2020The Layout in the razor view is the same to a Master page in ASP.NET Webforms and it is used to maintain the constant look and feel throughout the entire application. Take an example to create Layouts in asp.net MVC razor view engine.
Adding Layout
It starts with adding layout in Shared folder and for adding layout just right click on the shared folder and select View from it
When we click on View from the list a new dialog will pop up for asking view name and we are adding view name as _layoutdemo.cshtml.
After giving name just click on Add button then our layout view (_layoutdemo.cshtml) will create in a shared folder like as shown below
Now we will open our layout file(_layoutdemo.cshtml) which would contain code given below
Adding RenderSection in Layout
Now add RenderSection on Layout which we have created (_layoutdemo.cshtml). Usually, RenderSection will be placed in our Layout like @RenderSection. Syntax of RenderSection is:-
The RenderSection will render the content of the named section and specifies whether the section is required or not and RenderSection() is optional in the Layout view. Now we are adding headers and footers section which would be like as shown below
After we add RenderSection in our layout page (_layoutdemo.cshtml) then it will be like as shown below
In the above code, we have RenderBody() property and it works as ContentPlaceHolder that we use in asp.net webforms and render the portion of the child view that is not within a named section. The Layout view must include the RenderBody() method.
Now after completion of adding RenderSections in Layout now we will add a Controller and View
Adding Controller
Now add Controller and naming it as TestRazorController for that right click on Controllers folder select Add click on controller Give name as TestRazorController and select template as Empty MVC Controller and click add.
Adding View
After adding controller we will add a view for TestRazorController with name Index for that right click on controller select Add View and give name as Index and click Add.
Adding Section in View and Rendering Sections
Now we will add Section in Index.cshtml the @section is for defining a content to override from a shared view and here we will add 2 sections in this view one is Header and another one is Footer. Our @Section syntax will be like as shown below
We need to define Layout which we are going to use in our view like as shown below
In case if we didn't define the Layout option we will get an error.
After adding both header and footer sections and layout options our view Index.cshtml will be like as shown below
Run the Index page and check how our view looks like that would be like as shown below
In this way, we can use Layouts in our asp.net MVC application.