user4905335
user4905335

Reputation: 371

How to remove an HTML element from the Layout for a 1 particular page?

I'm new to ASP.NET MVC and am wondering what I should be doing if I my _Layout.cshtml has an element

<div class="navbar navbar-inverse navbar-fixed-top">
   ...
</div>

that I don't want generated for a particular page with controller SomePageController.cs and view SomePage.cshtml. Do I just wrap that piece of HTML in an if statement like

@if(not on SomePage) {
    <div class="navbar navbar-inverse navbar-fixed-top">
       ...
    </div>
}

or is there a more proper way?

Upvotes: 3

Views: 4361

Answers (4)

Brad C
Brad C

Reputation: 2982

I usually use a magic string in ViewBag for this. I set it in my controller (or you can do it in the top of the view, if you wish).

ViewBag.HideNavBar = true;

in the _Layout:

@if(ViewBag.HideNavBar == null) {
    <div class="navbar navbar-inverse navbar-fixed-top">
       ...
    </div>
}

I use this strategy to pass options into the layout (such as datepicker options) all the time.

Upvotes: 4

Zohaib Waqar
Zohaib Waqar

Reputation: 1239

you can do it multiple way

1: Simple trick.. just use If condition and get the route name from Query string and match it with your route .

2: use two different layouts. one with that HTML part and one without HTML part. and when creating view just specify the layout without HTML.

3: Use ViewBag / tempData

Approaches:

First:

if(Request.QueryString["routeName"] != "MyRoute" )
{
   //Render HTML Part
}

second:

@{
 layout = "~/shared/LayoutWithoutHTML.cshtml";
}

Third

in your Controller where you want to hide HTML

viewBag.HTMLCheck = true;

In your View

if(viewBag.HTMLCheck != true)
{
  // Html Part
}

Upvotes: 1

Donald
Donald

Reputation: 1200

Your solution seems like an appropriate way to go about it - ideally though, if it's not going to be on every page, the pages without that section should use a different Layout.

Upvotes: 0

CodeCaster
CodeCaster

Reputation: 151654

Give the single page that doesn't need that <div> a different Layout:

@model Foo
@{
    Layout = "~/Views/Shared/_LayoutWithoutNavigation.cshtml";
}

<!-- rest of HTML --> 

Upvotes: 1

Related Questions