Shared Layout page

  1. Create a Shared folder under Views folder. (Views (.cshtml file) created under any other specific folder like 'Product' (Product\Index.cshtml) would be used by Product controller to return this view by default per MVCs convention over configuration approach. Hence its important to create shared layouts under Shared folder).

  2. Create a layout template file e.g. MyLayout.cshtml

  3. Add the common HTML content in the above file

  4. Any content that needs to filled up by the page specific views would be rendered inside the @renderBody() or @renderSection("titleSection").

@{
    Layout = null
}
<html>
    <meta name="viewport" content="width=device-width" />
    <title> @renderSection("titleSection")
<html>
<body>
    <div>
        <div>
            @renderSection("topNavBar")
        </div>
        <div class="col-3">
            @renderSection("sidemenu")
        </div>
    <div>
    @renderBody()
</body>
  1. With @renderBody, anything thats in the view would be rendered

  2. As a good practice, use @renderSection instead of @renderBody

  3. In the View's cshtml file, specify that its going to use a shared template with below code:

Product\Index.cshtml

@using MyApp.ViewModels;
@model ProductVM
@{
    Layout = "~/Views/Shared/MyLayout.cshtml"
}
<div>
    Product Name: @Model.ProdName
    Unit Price: @Model.UnitPrice
</div>

@section titleSection{
    <b> Product Details </b>
}

Last updated

Was this helpful?