Inherited layout in ASP.NET MVC

北城以北 提交于 2019-12-12 08:23:20

问题


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 file a modified it a bit, but it would mean to duplicate the code and maintain two layout with 99% of same code.

I would like to inherit the layout from the default like this:

LayoutInherited.cshtml:

Layout = "~/Views/Shared/_Layout.cshtml";
ViewBag.BodyContentClassSpecial = "";

@section header{
<style>
    #body-content {
        width: 90%;
        margin: 0 auto;
    }
</style>

}

It is possible to do something like this?


回答1:


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/



来源:https://stackoverflow.com/questions/39960821/inherited-layout-in-asp-net-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!