ASP.NET MVC Layouts

What are Layouts in ASP.NET MVC?

ASP.NET MVC Layouts are used to maintain a consistent look and feel across multiple views within ASP.NET MVC application. As compared to Web Forms, layouts serve the same purpose as master pages, but offer a simple syntax and greater flexibility. A basic structure of layout is given below:

mvc-layout-syntax
 

You can use a layout to define a common template for your site. A layout can be declared at the top of view as:

mvc-layout-declaration

What are different ways of rendering layout in ASP.NET MVC?

There are following four different ways of rendering layout in ASP.NET MVC:

1. Using _ViewStart file in the root directory of the Views folder: The _ViewStart file with in Views folder is used to server the default Layout page for your ASP.NET MVC application. You can also change the default rendering of layouts with in _ViewStart file based on controller as shown below:

mvc-layout-root-directory

2. Adding _ViewStart file in each of the directories
You can also set the default layout for a particular directory by putting _ViewStart file in each of the directories with the required Layout information as shown below:

mvc-layout-each-directory

3. Defining Layout with in each view on the top

mvc-layout-view-level

4. Returning Layout from ActionResult

mvc-layout-action-result-level
 

What is the advantage of using MVC Layouts?

Layout views provide the advantage of maintaining consistent look and feel across all the views in an MVC application. A typical layout view consists of

MVC Layout

Rather than having all of these sections, in each and every view, we can define them in a layout view and then inherit that look and feel in all the views.

With layout views, maintaining the consistent look and feel across all the views becomes much easier, as we have only one layout file to modify, should there be any change. The change will then be immediately reflected across all the views in entire application.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *