Introduction
When you visit a website, you see that some part of the page remains the same whenever you scroll the website or redirect to some part of the same website.
So if the part has to be exact, why do we need to write the whole code again and again? Is there any solution to this problem?
The answer is Yes. We can use layouts to solve this problem and how to use that we will see in this blog.
So without wasting any further time, let’s get on with our topic.
What is Layout and its Need
One can understand Layout as the Common UI between different pages and views. These can be compared with the master pages in Webforms applications. In simple words, the Layout is a common view while moving within a webpage or across the same web page.
Need of Layout
Most of the websites in today’s time have the following four components:
- Website Handler
- Left Navigation Menus
- Main Content Area
- Website Footer
Suppose you do not follow the Layout. You have to write code for all these four components when creating a view. This will increase your code length multiple times and make your application difficult to maintain. This will violate the DRY principle, i.e., Don't Repeat Yourself, as we repeatedly repeat the code.
Let’s understand this with an example. Suppose you want to add or delete something in the navigation bar, then you have to change it for each view you have created till now.
So instead of copying the same HTML content in every view file, it is advisable to add the HTML code in a layout file and inherit that layout file in every view. This will drastically save time and reduce the code length. So if now you want to make any changes, you have to do that in the layout file, and it will automatically be reflected in every view which has inherited the layout file.
Layout View in ASP.NET Core MVC Application:
- It is also a file with a .cshtml extension like the regular files in ASP.NET.
- You can relate it with the master page in the web forms application of ASP.NET.
- We place the Layout in the subfolder in the Views folder with the name shared as they are not specific to any controller.
- The default name for the layout view file in ASP.NET is _Layout.cshtml.
- The underscore before the name describes that these files cannot be served/ used directly by the browser.
- One of the advantages of using ASP.NET is that we can create many layouts files for a single application.