Layout View in ASP.NET Core MVC

SPONSOR AD

Layout View in ASP.NET Core MVC

In this article, I am going to discuss the Layout View in ASP.NET Core MVC Web Application with Examples. Please read our previous article, where we discussed Attribute Routing in ASP.NET Core MVC Applications with examples. As part of this article, we are going to discuss the following pointers.

  1. What is Layout View in ASP.NET Core MVC?
  2. Why Do We Need Layout View in ASP.NET Core MVC?
  3. How Do We Create a Layout View in ASP.NET Core MVC?
  4. Understanding the _Layout.cshtml file.
  5. How to Use Layout View in ASP.NET Core MVC Application?
  6. Advantages and Disadvantages of Layout View in ASP.NET Core MVC.
What is Layout View in ASP.NET Core MVC?

The common UI code, which can be used in many views, can go into a common view called layout in ASP.NET Core MVC Application. In ASP.NET Core MVC, the layout view plays an important role in maintaining a consistent look and feel across different pages of a web application. It allows you to define a common site template, which can be applied to multiple views, thus promoting code reusability and reducing duplication.

  • Layout View: A special Razor view that contains HTML layout elements shared across multiple pages, such as headers, footers, navigation menus, and sidebars. It acts as a master page or template for other views.
  • Purpose: To provide a consistent layout to the web application, enabling a single point of modification for the layout elements that are common across pages.
Why Do We Need Layout View in ASP.NET Core MVC?

The layouts in ASP.NET Core MVC Applications help us maintain a consistent look across all the pages or views of our application. Nowadays, most web applications have a common layout that provides a consistent user experience when the user navigates from one page to another. The layout typically includes common user interface elements such as:

  1. Website Header
  2. Website Footer
  3. Navigation Menus
  4. Main Content Area

Please look at the following diagram, which shows the above-mentioned four areas on a website.

SPONSOR AD

Why do we Need Layout View in ASP.NET Core MVC?

If you don’t have a layout view for your website, then you need to repeat the required HTML for the above-mentioned sections in each and every view of your application. This violates the DRY (Don’t Repeat Yourself) principle as we are repeating the same code in multiple views.

As a result, it isn’t easy to maintain the application code. For example, suppose you have to remove or add a menu item from the list of navigation menus or even if you want to change the header or footer of your website. In that case, you need to do this in every view, which is tedious, time-consuming, and error-prone.

Instead of putting all the sections (i.e., the HTML) in every view page, it is always better and advisable to put them in a layout view and then inherit that layout view in every view where you want that look and feel. With the help of layout views, it is now easier to maintain your application’s consistent look and feel. This is because if you need to make any changes, you need to do it only in one place, i.e., in the layout view, and the changes will be reflected immediately across all the views inherited from the layout view.

Layout View in ASP.NET Core MVC Application:
  1. Like the regular view in ASP.NET Core MVC, the layout view is also a file with a .cshtml extension
  2. If you are coming from an ASP.NET Web Forms background, you can think of the layout view as the master page of the ASP.NET Web Forms application. If you are coming from ASP.NET MVC Background, it is similar to the layout view we use in ASP.NET MVC Web Applications.
  3. As the layout views are not specific to any controller. As the layout view will be used across multiple views of our application, we usually place the layout views in a Shared subfolder within the Views folder.
  4. By default, in the ASP.NET Core MVC Application, the layout view file is named _Layout.cshtml. But you can change the name if you wish.
  5. The leading underscore in the file name indicates that these files are not intended to be served directly by the browser.
  6. In ASP.NET Core MVC, creating multiple layout files for a single application is possible. For example, you may have one layout file for the admin users and another layout file for non-admin users of your application.
How Do We Create a Layout View in ASP.NET Core MVC Application?

First, create a new ASP.NET Core Application with the name FirstCoreMVCApplication using the Model-View-Controller Template. Next, to create a layout view in ASP.NET Core MVC, follow the steps below.

  1. Right-click on the “Views” folder and then add a new folder with the name “Shared” if not already added. If you are creating the ASP.NET Core Web Application using Model-View-Controller, the Shared folder will be there with the _Layout.cshtml file by default.
  2. Next, Right-click on the “Shared” folder and then select the “Add” – “New Item” option from the context menu, which will open the Add New Item window.
  3. From the “Add New Item” window, search for Layout and then select “Razor Layout” give a meaningful name (_Layout.cshtml) to your layout view and finally, click on the “Add” button as shown below, which should add _Layout.cshtml file within the Shared folder.

How to Create a Layout View in ASP.NET Core MVC Application

Note: In this article, I am going to show you how to create and use a layout file, and in our upcoming articles, I will show you how to use a website header, footer, and navigation menus. So, once you add the _Layout.cshtml file, your Views folder should look as shown below.

SPONSOR AD

Views Structure in ASP.NET Core MVC Application

Understanding the _Layout.cshtml file:

Let us first modify the _Layout.cshtml file as follows.

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
</head>
<body>
    <div>
        @RenderBody()
    </div>
</body>
</html>

As you can see in the above layout file, it contains the standard HTML, head, title, and body elements. As the above elements are present in the layout file, you don’t have to repeat them in each and every view of your application that uses the above Layout file.

The View or Page-Specific title is retrieved by using the @ViewBag.Title expression. For example, when the “index.cshtml” view is rendered using this layout view, then the index.cshtml view will set the Title property on the ViewBag. This is then retrieved by the Layout view using the expression @ViewBag.Title and set as the value for the <title> tag.

The @RenderBody() method specifies the location where the View or Page-Specific content is going to be injected. For example, if the “index.cshtml” view is rendered using this layout view, then index.cshtml view content is injected at the @RenderBody() location.

Now, let us again modify the _Layout.cshtml page as shown below to include the header, footer, left navigation menus, and main content area section.

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
</head>
<body>
    <table border="1" style="width:800px; font-family:Arial">
        <tr>
            <td colspan="2" style="text-align:center">
                <h3>Website Header</h3>
            </td>
        </tr>
        <tr>
            <td style="width:200px">
                <h3>Left Navigation Menus</h3>
            </td>
            <td style="width:600px">
                @RenderBody()
            </td>
        </tr>
        <tr>
            <td colspan="2" style="text-align:center; font-size:x-small">
                <h3>Website Footer</h3>
            </td>
        </tr>
    </table>
</body>
</html>
Configuring MVC Services and Middleware in the Main Method of the Program class:

Please modify the Main method of the Program class as shown below to configure the required MVC services and Middleware Components. Here, we are using the AddControllersWithViews method to configure MVC services. We have also used UseRouting and MapControllerRoute middleware components to configure the Routing and MVC Middleware to the Request Processing Pipeline. Also, we set the Home controller and Index action method as the default route for our application.

namespace FirstCoreMVCApplication
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.
            builder.Services.AddControllersWithViews();

            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (!app.Environment.IsDevelopment())
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");

            app.Run();
        }
    }
}
Modifying the Home Controller:

By default, the Home Controller class is created. So, please modify the Home Controller as shown below. As you can see, we have created the Home Controller class with two action methods, i.e., Index and Details. Both the action methods return a view.

SPONSOR AD
using Microsoft.AspNetCore.Mvc;
namespace FirstCoreMVCApplication.Controllers
{
    public class HomeController : Controller
    {
        public ViewResult Index()
        {
            return View();
        }
        
        public ViewResult Details()
        {
            return View();
        }
    }
}
How to Use Layout View in ASP.NET Core MVC Application?

Now, we are going to create the Index and Details views using the Layout view. In order to render a view using the layout view (_Layout.cshtml), we need to set the Layout property.

Index.cshtml:

Please modify the Index.cshtml view as shown below to use the layout view. Here, we are setting the Page Title using the ViewBag.Title property, i.e., ViewBag.Title = “Home Page”; and we are also setting the Layout for our view as Layout = “~/Views/Shared/_Layout.cshtml”;

@{
    ViewBag.Title = "Home Page";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h1>Home Page</h1>
Details.cshtml:

Please create the Details.cshtml view within the Home folder and then copy and paste the following code to use the layout view. Here, we are setting the Page Title using the ViewBag.Title property, i.e., ViewBag.Title = “Details Page”; and we are also setting the Layout for our view as Layout = “~/Views/Shared/_Layout.cshtml”;

@{
    ViewBag.Title = "Details Page";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h1>Details Page</h1>

Now run the application and navigate to the Home/Index URL, which should display the page below.

Layout View in ASP.NET Core MVC

Next, navigate to the Home/Details URL, which should display the page below.

Layout Files in ASP.NET Core MVC Application

Now, if you compare both pages, you will see that only the Page Title and Main Content area are changed; the rest, like the Footer, Menus, and Header, will be the same. Here, we are not repeating the HTML code in both the Index and Details View; rather, we are using the Layout view, which contains the common HTML Elements.

Structure of Layout View in ASP.NET Core MVC:

Structure of Layout View

Advantages and Disadvantages of Layout View in ASP.NET Core MVC

Layout views in ASP.NET Core MVC provide a consistent structure for rendering the common parts of your application’s UI, such as headers, footers, navigation bars, and sidebars. While layout views offer several advantages, they also come with a few potential disadvantages:

SPONSOR AD
Advantages of Layout Views:

The Layout view in ASP.NET Core MVC serves several purposes in web development, enhancing the efficiency, maintainability, and consistency of web applications. Here’s a breakdown of why Layout views are essential:

  • Consistency Across Pages: Layout views provide a single place to define elements that are common across multiple pages of a web application, such as headers, footers, navigation menus, and CSS/Javascript references. This ensures a consistent look and feel across the entire application, which is crucial for user experience and brand identity.
  • Reduce Code Duplication: Centralizing common elements in a Layout view reduces code duplication. Without a Layout view, each page would need to include its own definitions of these common elements, leading to repeated code across multiple views. Reducing code duplication simplifies maintenance, as changes to these common elements only need to be made in one place.
  • Simplify Maintenance: When the design or structure of the common elements needs to change, developers can make changes in the Layout view, and those changes will automatically apply to all views that use it. This simplification greatly reduces the effort required to update and maintain the application.
  • Enhanced Structuring and Organization: Layout views allow developers to define a clear structure for web pages. By using sections and render methods like RenderBody(), RenderSection(), or RenderPartial(), developers can designate areas within the Layout for dynamic content that specific pages can fill in. This structured approach helps in organizing content and functionality neatly.
  • Improved Development Efficiency: With the heavy lifting for common elements handled by the Layout view, developers can focus on the unique content of each page, improving development speed and efficiency. This separation of concerns makes it easier for teams to work in parallel, with some focusing on layout design and others on page-specific content.
  • Support for Responsive Design: Layout views can include responsive design elements using CSS frameworks like Bootstrap. This means the application can provide a consistent user experience across different devices and screen sizes, with minimal additional effort for each page.
  • Better Performance: By centralizing and reusing common elements, Layout views can contribute to better overall performance of the web application. For example, by defining scripts and stylesheets in the Layout view, you ensure that these resources are loaded once and cached by the browser rather than being loaded separately on each page.
Disadvantages of Layout Views:

While Layout views in ASP.NET Core MVC offer numerous advantages, there are also some disadvantages or challenges that developers might encounter:

  • Overhead for Small Applications: For very small or single-page applications, the overhead of implementing and managing a Layout view might not be suitable. In such cases, the simplicity of a single view without a separate Layout could be more efficient.
  • Complexity in Highly Dynamic Layouts: If an application requires highly dynamic layouts that change significantly across different pages, managing these variations through a single Layout view can become complex. This might need conditional logic within the Layout view or multiple Layout views, complicating the application structure.
  • Difficulty in Debugging: Debugging issues related to content rendering within a Layout view can sometimes be more challenging, especially if the content is dynamically generated or multiple sections are involved. Identifying whether an issue originates from the Layout view, a specific view, or the interaction between them can require additional effort.
  • Performance Considerations: While Layout views can improve performance by centralizing common resources, improper use (like overly complex conditional logic or heavy content in the Layout) can negatively impact performance. For example, loading large scripts or stylesheets that are not used by all pages can increase load times unnecessarily.
  • Risk of Over-generalization: There’s a risk of making the Layout view too generic in an attempt to cover all use cases. This over-generalization can add unnecessary elements to pages where they are not needed, affecting both performance and user experience.

So, layout views offer a way to maintain consistency, reduce duplication, and organize your application’s UI. However, they might not be suitable for every project or scenario.

That’s it for today. In the next article, I am going to discuss Layout Page Sections in ASP.NET Core MVC Applications. This article explains How to Create and Use Layout View Files in ASP.NET Core MVC Applications with Examples.

SPONSOR AD

Leave a Reply

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