Conditionally displaying partial views based on active page

on3al picture on3al · Jun 17, 2014 · Viewed 16.7k times · Source

I'm trying to get familiar with ASP.net MVC5 and am porting over an existing website.

I have defined a default shared layout view that contains several partials for things like the header, navigation, footer, etc...

The only difference between my home page, and other pages using this layout is the homepage has a slider and a few other unique features. Other than that the layout is identical.

Because of this, I don't think it warrants creating two different views and setting the layout for the home page to use one view, and all other pages to use another when most of the template is identical.

I have created a partial named _HomeContentPartial containing the unique content for the home page.

What is the best way in Razor to conditionally include this partial only if my home (index action on my home controller) is the current page?

Answer

Gone Coding picture Gone Coding · Jun 17, 2014

Simply add a ViewBag.IsHome = true; to the home controller, index action method controller.

Then add this to the _layout.chtml view:

   @if ((bool?)ViewBag.IsHome){
        Html.RenderPartial( "_HomeContentPartial .cshtml" );
   }

Another option:

As you can specify as many render regions as you like in a layout, simply put in placeholders for the optional parts and use @RenderSection with the required flag set to false so that it does not mind if it is missing.

e.g. in your _layout.cshtml

@RenderSection("extraheader", false)

then in a view that has optional parts to insert in that position:

@section extraHeader{
   <ul>
     <li>Some new option 1</li>
     <li>Some new option 2</li>
   </ul>
}

Which method you use will depend on how you want to reuse components. You can happily render a partial view inside an @section to allow reuse across many views:

e.g.

@section extraHeader{
   @Html.Partial("somepartialview")
}

or even using another controller action (better encapsulation, so my preference):

e.g.

@section extraHeader{
   @Html.Action("someAction", "someController", new {id = someValue})
}