Add/remove html 根据RenderBody()的内容标记

Add/remove html markups according to the content of RenderBody()

在我的 _Layout.cshtml:

<section class="container content-section text-center">
    @RenderBody()
</section>

我只想在 "body" 不是主页时显示 "section"。

我正考虑检测 url,但很快意识到我将有许多绑定到网站的 Url,这不是明智的做法。

那么我可以做些什么来让 "section" 包装器更智能,知道什么时候出现什么时候不出现?

谢谢。

您可以检查哪个控制器当前正在执行其操作并检查主页控制器:

@{
    var controllerName = ViewContext.RouteData.Values["controller"].ToString();
    var actionName = ViewContext.RouteData.Values["controller"].ToString();
}

@if(controllerName == "HomePage" && actionName == "yourActionName")
{

    @RenderBody()

}
else
{
<section class="container content-section text-center">
@RenderBody()
</section>
}

至于我,我不会使用条件。 它是一种 hack 不是解决方案 。下次有什么需要改的时候,你会加越来越多的IF吗?

使用两种布局。

_LayoutWithSection.cshtml:

 // ...
 <section class="container content-section text-center">
     @RenderBody
 </section>
 // ...

_Layout.cshtml:

 // ...
 @RenderBody
 // ...

Home/Index.cshtml:

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

_ViewStart.cshtml:

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