Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide specific element on page from _Layout.cshtml page

I work on mvc 5 project.

On my _Layout.cshtml I have html element named id="topBar" this element displayed in each page.

But I have page named About.cshtml I don't want this page to display only element id="topBar" all other html elements in _Layout.cshtml I want them to be displayed normal in About.cshtml.

Any idea how can achieve described appearance above?

like image 743
Michael Avatar asked Feb 22 '17 10:02

Michael


2 Answers

One simple way of achieving this (without javascript), is to set a value in ViewBag inside your about Action and use it in layout like this:

_Layout.cshtml

@if (ViewBag.ShowTopBar ?? false)
{
    <div id="topBar">

    </div>
}

Action inside your Controller:

public class MyAwesomeController : Controller
{

    public ActionResult About()
    {
        ViewBag.ShowTopBar = true;
        return View();
    }

}
like image 119
Alisson Reinaldo Silva Avatar answered Oct 13 '22 02:10

Alisson Reinaldo Silva


There are two options:

1. Add an ID to every body element

You could add an ID to the body of each of your pages that contains for example the Controller and Action name and then add a CSS rule to hide the topBar element on the about page.

First, let's create two string variables for the controller and action name. Do this in your _Layout.cshtml:

@{
    string controller = ViewContext.RouteData.Values["controller"].ToString();
    string action = ViewContext.RouteData.Values["action"].ToString();
}

Next, add the ID to the body:

<body id="@controller-@action">

In your css, you can now add a rule to hide the topbar in the about page (assuming the controller is called HomeController):

#Home-About #topBar {display:none;}

You could also use an extension method to get the controller and action name. For example something like this.

2. Use jQuery on the About page

You could add a Javascript on your about page and use jQuery to hide the topbar (I assume jQuery is already loaded):

<script>
   $("#topBar").hide();
</script>
like image 39
jao Avatar answered Oct 13 '22 01:10

jao