开发者

Conditional Layouts in ASP.NET MVC 3

开发者 https://www.devze.com 2023-04-08 15:29 出处:网络
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:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消