在我的_Layout.cshtml中:
<section class="container content-section text-center">
@RenderBody()
</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
// ...
首页/Index.cshtml:
@{
Layout = "~/Views/Shared/_LayoutWithSection.cshtml";
}
// ...
_ViewStart.cshtml:
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
// ...