Tuesday, 22 March 2022

Layout View in ASP.NET Core MVC

 # Layout View in ASP.NET Core MVC

1. Just like a regular view a layout view is also a file on the file system with a .cshtml extension
2. You can think of a layout view as a master page in asp.net web forms.
3. Since a layout view is not specific to a controller, we usually place the layout view in a sub folder called "Shared" in the "Views" folder
4. By default, in ASP.NET Core MVC, the layout file is named _Layout.cshtml.
5. In ASP.NET Core MVC, the file names of other .cshtml files like _ViewStart.cshtml and _ViewImports.cshtml start with an underscore.
6. The leading underscore in the file name indicates that these files are not intended to be served directly by the browser.
7. It is also possible to have multiple layout files in a single application. Perhaps one layout file for all admin users and a different layout file for all non admin users.
8. @RenderBody() is the location where view specific content is injected. For example, if index.chtml view is rendered using this layout view, index.cshtml view content is injected at the location where we have @RenderBody() method call.
9. To render a view using the layout view (_Layout.cshtml) set the Layout property. For example, to use the Layout view with details.cshtml, modify the code in details.cshtml to include the Layout property as shown below.
10. set different layout for different role
 @{
    if (User.IsInRole("Admin"))
    {
        Layout = "_AdminLayout";
    }
    else
    {
        Layout = "_NonAdminLayout";
    }
}

## Section in a Layout View

1. A layout page in ASP.NET Core MVC can also include a section. A section can be optional or mandatory. It provides a way to organize where certain page elements should be placed.
2. If the custom script file is required by all the views then we could place it in the Layout page as shown below.
 <body>
    <div>
        @RenderBody()
    </div>

    <script src="~/js/CustomScript.js"></script>
</body>
3. In layout view,
 @if (IsSectionDefined("Scripts"))
{
    @RenderSection("Scripts", required: false)
}
4. in child view, we want the details view to include <script> tag in the "Scripts" section in the layout page. To achieve this we include "Scripts" section in Details.cshtml as shown below.
@section Scripts {
    <script src="~/js/CustomScript.js"></script>
}

No comments:

Post a Comment

Search This Blog

Creating your first "Alexa" Skill

Index What is Alexa What is Alexa Skill? Why is it required when Alexa already equipped with voice assistant? Dev...