Define a shared cshtml file and render it on a sub page in asp net core mvc

Introduction

ASP.NET is a popular language used for building web applications. In this article, we will discuss how to define a shared cshtml file and render it on a sub page in ASP.NET Core MVC.

a Shared cshtml File

A shared cshtml file is a view file that can be reused across multiple pages in an ASP.NET Core MVC . It allows you to define UI or layouts that can be shared among different views.

To define a shared cshtml file, you can create a new folder “Shared” in the “Views” folder of your ASP.NET Core MVC project. Inside the “Shared” folder, create a new cshtml file, for example, “SharedLayout.cshtml”.


// SharedLayout.cshtml




    Shared Layout


    
@RenderBody()

In the above example, we have defined a HTML layout for our shared cshtml file. The “@RenderBody()” directive is used to render the content of the sub page within the shared layout.

Rendering the Shared cshtml File on a Sub Page

Once you have defined the shared cshtml file, you can render it on a sub page by specifying the layout in the sub page's cshtml file.

For example, let's say we have a sub page called “HomePage.cshtml” that needs to use the shared layout. To render the shared layout on the “HomePage.cshtml” page, you can add the following code at the top of the file:


@{
    Layout = "~/Views/Shared/SharedLayout.cshtml";
}

By the “Layout” property to the path of the shared layout file, the “HomePage.cshtml” page will use the shared layout for rendering.

Now, any content you add to the “HomePage.cshtml” file will be rendered within the shared layout defined in the “SharedLayout.cshtml” file.

Conclusion

In this article, we have discussed how to define a shared cshtml file and render it on a sub page in ASP.NET Core MVC. By shared cshtml files, you can easily common UI elements or layouts across multiple views, improving code reusability and maintainability in your ASP.NET Core MVC application.

Rate this post

Leave a Reply

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

Table of Contents