Inherited layout in ASP.NET MVC

后端 未结 1 1699
天涯浪人
天涯浪人 2021-02-13 01:17

I have default layout _Layout.cshtml for the most pages. However for some group of pages I would like to have slightly modified default layout. I know I could just copy that fil

相关标签:
1条回答
  • 2021-02-13 01:52

    Yes, layout inheritance is possible. Essentially, you're just creating a layout that itself utilizes a layout, since layouts are just views, there's no issues with that.

    You pretty much do it exactly as you described:

    _SubLayout.cshtml

    @{
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
    
    @RenderBody()
    

    A few things to keep in mind:

    1. The content of the sub-layout will be placed where you have @RenderBody in your base layout, just as the content of a view would be. Your sub-layout still needs its own @RenderBody to determine where the content of the view that utilizes it should be placed.

    2. Any sections defined as required in your base layout must be implemented in your sub-layout or Razor will raise an exception, just as if your view did not implement the section. For example:

      _Layout.cshtml

      @RenderSection("Foo", required: true)
      

      _SubLayout.cshtml

      @section Foo
      {
          <p>Foo</p>
      }
      
    3. If your view needs to be able to implement a section (required or not), the sub-layout must define it. For example, in the code above, any view using _SubLayout.cshtml would not be able to define a Foo section, because it would no longer exist. An exception would be raised if you tried. In order to allow that view to define that section you would have to do something like the following:

      _SubLayout.cshtml

      @section Foo
      {
          @RenderSection("Foo", required: true)
      }
      

      This defines the section for the purpose of the base layout and then allows the section to be defined by any view that uses this sub layout.

    There's actually a post on my blog that goes into all this in much greater detail if you need it: http://cpratt.co/how-to-change-the-default-asp-net-mvc-themet/

    0 讨论(0)
提交回复
热议问题