Umashankar
Umashankar

Reputation: 709

How to override the @section in MVC Razor

Please help me to fix this issue. I have two files BaseLayout.cshtml and the second one is ExtendedLayout.cshtml file for overriding the base content of HTML CSS. I need to run the extended section of extendedLayout.cshtml file if same section is present in override otherwise base would work. Same as OOPS override concept.

Base Layout CSS Code

@section HeadCssSection {
   @*Base Layout CSS *@
   @Styles.Render("~/Content/BaseCSS")
   @RenderSection("HeadCssSection")

}

Extended Layout CSS Code

@section HeadCssSection {
    @Styles.Render("~/Content/ExtendedCSS")
    @RenderSection("HeadCssSection") 
}

Please help me to fix this issue

Upvotes: 4

Views: 2232

Answers (2)

Amol
Amol

Reputation: 351

In Base layout, write the code like this.

@section HeadCssSection {
   @if (IsSectionDefined("HeadCssSection"))
   {
       @RenderSection("HeadCssSection")
   }
   else
   {
       @Styles.Render("~/Content/BaseCSS")
   }
}

Define this HeadCssSection in extended layout so that it will take extended layout code. And if you want to run the code of base layout, then put the code in else condition.

Upvotes: 1

hasan
hasan

Reputation: 3502

You can use isSectionDefined() like following

@if (!IsSectionDefined("HeadCssSection")) { 
    RenderSection("HeadCssSection") 
}

Upvotes: 2

Related Questions