gpt4 book ai didi

asp.net-mvc - ASP.NET MVC 3 中的条件布局

转载 作者:行者123 更新时间:2023-12-03 06:11:08 25 4
gpt4 key购买 nike

因此,对于 MVC3 中的布局,可以说我希望能够在页面级别上指定是否显示特定部分,最好的方法是什么。考虑以下页面:

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

@section LetsBeFriends {

}

@section Header {
....
}

@section Body {
....
}

为了使 LetsBeFriends 部分成为有条件的,我实现了如下布局:

@{
if (IsSectionDefined("LetsBeFriends"))
{
@RenderSection("LetsBeFriends")
@Html.Partial("_LetsBeFriends")
}
}

@RenderSection("Body")

这看起来很奇怪,因为 LetsBeFriends 始终是一个空部分,它只是决定是否渲染部分的条件。有更好的办法吗?

最佳答案

为什么不使用ViewBag?在您的页面中:

@if (friendsCondition)
{
ViewBag.LetsBeFriends = true;
}

然后,在 _Layout.cshtml 中:

@if (Viewbag.LetsBeFriends)
{
@Html.Partial("_LetsBeFriends")
}

但是,最好在 Controller 操作中设置它,而不是在 View 中。

关于asp.net-mvc - ASP.NET MVC 3 中的条件布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7537026/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com