So with layouts in MVC3 lets say I want to be able to specify on a page level if a particular section is displayed, what is the best way to go about it. Consider the following page:
@{
ViewBag.Title = "...";
Layout = "~/Views/Shared/Layout/_开发者_开发知识库Layout.cshtml";
}
@section LetsBeFriends {
}
@section Header {
....
}
@section Body {
....
}
For the LetsBeFriends section to be conditional I have implemented the layout like this:
@{
if (IsSectionDefined("LetsBeFriends"))
{
@RenderSection("LetsBeFriends")
@Html.Partial("_LetsBeFriends")
}
}
@RenderSection("Body")
This seems hacky because LetsBeFriends will always be an empty section, its just a condition to decide whether to render the partial. Is there a better way?
Why not use the ViewBag? In your page:
@if (friendsCondition)
{
ViewBag.LetsBeFriends = true;
}
Then, in _Layout.cshtml:
@if (Viewbag.LetsBeFriends)
{
@Html.Partial("_LetsBeFriends")
}
However, it is even better to set this in the controller action, rather than the view.
精彩评论