Conditionally display partial views based on the active page

I am trying to get to know ASP.net MVC5 and migrate an existing website.

I defined the general layout of the default layout, which contains several partial layouts for things like heading, navigation, footer, etc.

The only difference between my homepage and other pages using this layout is a page with a slider and several other unique features. In addition, the layout is identical.

Because of this, I do not think that this guarantees the creation of two different views and setting the layout for the main page to use one view, and all other pages for the other, when most of the template is identical.

I created a partial name _HomeContentPartial containing unique content for the main page.

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

+6
source share
1 answer

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

Then add this to the _layout.chtml :

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

Another option:

As you can specify as many rendering areas as you want in the layout, just add placeholders for the extra parts and use @RenderSection with the required flag set to false so that it doesn't mind if it's missing.

eg. in your _layout.cshtml

@RenderSection ("extraheader", false)

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

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

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

eg.

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

or even using another controller action (encapsulation is better, so I prefer):

eg.

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

Source: https://habr.com/ru/post/970920/


All Articles