Luke Belbina
Luke Belbina

Reputation: 5869

Conditional Layouts in ASP.NET MVC 3

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?

Upvotes: 6

Views: 3794

Answers (1)

counsellorben
counsellorben

Reputation: 10924

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.

Upvotes: 8

Related Questions