• Home
  • About
  • Contact
  • ado.net
  • angular
  • c#.net
  • design patterns
  • linq
  • mvc
  • .net core
    • .Net Core MVC
    • Blazor Tutorials
  • sql
  • web api
  • dotnet
    • SOLID Principles
    • Entity Framework
    • C#.NET Programs and Algorithms
  • Others
    • C# Interview Questions
    • SQL Server Questions
    • ASP.NET Questions
    • MVC Questions
    • Web API Questions
    • .Net Core Questions
    • Data Structures and Algorithms

Monday, August 31, 2020

Layout View in ASP.NET Core MVC

 Admin     August 31, 2020     .Net, .Net Core, .Net Core MVC, Asp.Net, C#     No comments   

In this article, I am going to discuss the Layout View in ASP.NET Core MVC Application. Please read our previous article where we discussed the Attribute Routing in ASP.NET Core MVC Application with examples. As part of this article, we are going to discuss the following pointers.
  1. Why do we need Layout View in ASP.NET Core MVC?
  2. What is a Layout?
  3. How to Create a Layout View in ASP.NET Core MVC Application?
  4. How to use a Layout View in ASP.NET Core MVC Application?
What is Layout?
The layouts are like the master pages in Webforms applications. The common UI code, which can be used in many views can go into a common view called layout.

Why do we need Layout View in ASP.NET Core MVC?
Nowadays, almost all web applications have the following sections.
  1. Website Header
  2. Website Footer
  3. Navigation Menus
  4. Main Content Area
Please have a look at the following image which shows the above mentioned four areas on a website.
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 is violating the DRY (Don’t Repeat Yourself) principle as we are repeating the same code in multiple views. As a result, it is very difficult to maintain the application. For example, if 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 then you need to do this in each and every view which is tedious, time-consuming as well as error-prone.

Instead of putting all the sections (i.e. the HTML) in each and every view page, it is always better and advisable to put them in a layout view and then inherit that layout view in each and every view where you want that look and feel. With the help of layout views, now it is easier to maintain the consistent look and feel of your application. This is because if you at all need to do any changes then 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 which are 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 ASP.NET Web Forms background, you can think of the layout view as the master page in asp.net web forms application.
  3. As the layout views are not specific to any controller, so, we usually place the layout views in a subfolder called “Shared” within the “Views” folder.
  4. By default, in ASP.NET Core MVC Application, the layout view file is named _Layout.cshtml.
  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, it is also possible to create multiple layout files for a single application. For example, you may have one layout file for the admin users and another layout file for non-admin users of your application.
How to Create a Layout View in ASP.NET Core MVC Application?
In order to create a layout view in ASP.NET Core MVC, you need to follow the below steps.
  1. Right-click on the “Views” folder and then add a new folder with the name “Shared“.
  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 meaning full 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 website header, footer, and navigation menus.

Understanding the _Layout.cshtml file:
Let us have a look at the auto-generated HTML code in the _Layout.cshtml file. The following HTML is auto-generated in the _Layout.cshtml file.
<!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, so you don’t have to repeat all the above elements in each and every view.

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() specifies the location where the view or page-specific content is injected. For example, if “index.cshtml” view is rendered using this layout view, then index.cshtml view content is injected at the location.

Let us 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="font-family: Arial; width: 800px;">
      <tr>  
            <td colspan="2" style="text-align: center;">
                <h3>Website Header</h3>
            </td>
      </tr>
      <tr>
            <td style="width: 200px;">
                <h3>Left Navigation Menus
            </td>
            <td style="width: 600px;">
                @RenderBody()
            </td>
      </tr>
      <tr>
            <td colspan="2" style="font-size: x-small; text-align: center;">
                <h3>Website Footer</h3>
            </td>
      </tr>
</table>
</body>
Modifying the Startup class:
Please modify the Startup class as shown below where we configure the required services for MVC.
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace FirstCoreMVCApplication
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseMvcWithDefaultRoute();
        }
    }
}
Modifying the Home Controller:
Please modify the Home Controller as shown below.
using Microsoft.AspNetCore.Mvc;
namespace FirstCoreMVCApplication.Controllers
{
    public class HomeController : Controller
    {
        public ViewResult Index()
        {
            return View();
        }
        
        public ViewResult Details()
        {
            return View();
        }
    }
}
As you can see here we have created two action methods i.e. Index and View.

Using 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), you need to set the Layout property.

Index.cshtml:
Please modify the Index view as shown below to use the layout view.
@{
    ViewBag.Title = "Home Page";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

Home Page

Details.cshtml:
Please modify the Details view as shown below to use the layout view.
@{
    ViewBag.Title = "Details Page";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

Details Page

Now run the application and navigate to the Home/Index URL which should display the page as shown below.
---------------------how to create and use layout files in ASP.NET Core MVC
That’s it for today. In the next article, I am going to discuss Sections in the layout page in ASP.NET Core MVC Application. Here, in this article, I try to explain the need and how to create and use layout files in ASP.NET Core MVC Application.

Summary:
I hope this post will be helpful to understand the concept of Layout View in ASP.NET Core MVC
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post

0 comments:

Post a Comment

If you like this website, please share with your friends on Facebook, Twitter, LinkedIn.

Join us on Telegram

Loved Our Blog Posts? Subscribe To Get Updates Directly To Your Inbox

Like us on Facebook

Popular Posts

  • What is Dependency Injection(DI)
    Hi friends! Today we are going to learn about Dependency Injection and in our last session we have come across Static classes and where it s...
  • C# Programming Examples on Sorting
    Today i am going to tell you some of the Sorting programming questions in C#. Q1- Write a C# program to perform Selection sort. Ans:  Sel...
  • Calling Web API Service in a Cross-Domain Using jQuery AJAX
    In this article, I am going to discuss Calling Web API Service in a Cross-Domain Using jQuery AJAX . Please read our previous article befor...
  • ViewBag in ASP.NET Core MVC
    In this article, I am going to discuss the use of ViewBag in ASP.NET Core MVC application with examples. Please read our previous article ...
  • Recursion And Back Tracking
    In this article, I am going to discuss Recursion And BackTracking in detail. Please read our previous article where we discussed Master Th...
  • What is Abstract Class and When we should use Abstract Class
    Hi friends! In our previous sessions we have seen  Difference Between Class and Struct . And in our last session  we learnt Usability of Sec...
  • Binary to Decimal Conversion in C# with Examples
    In this article, I am going to discuss the Binary to Decimal Conversion in C# with some examples. Please read our previous article where w...

Blog Archive

Contact Form

Name

Email *

Message *

Tags

.Net .Net Core .Net Core MVC Algorithm Angular Anonymous Types Asp.Net Asp.Net MVC Blazor C# Data Structure Database Design Patterns Entity Framework Entity Framework Core Filters Interview Question Management Studio Programming Programs SQL Server SSMS Web API

Copyright © C# Techtics | All Right Reserved.

Protected by Copyscape