0

So i am going off of this example:

better way to get active pages

What I'm trying to accomplish in my _Layout.cshtml is this:

<div id="navbar">
<div><a href="~/Home"><img src="~/Images/home_on.png" /></a></div>
<div><a href="~/Home"><img src="~/Images/home_off.png" /></a></div>
<div><a href="~/Home"><img src="~/Images/contact_on.png" /></a></div>
<div><a href="~/Home"><img src="~/Images/contact_off.png" /></a></div>
</div>

The navbar div changes depending on the active page. If its home, then show "home_on.png" div. If its not display "home_off.png" and so forth.

Community
  • 1
  • 1
  • What is your question or problem? Can you post the rest of the relevant code? – Daniel Hoffmann-Mitscherling Jul 15 '15 at 01:29
  • I've posted a potential answer, but I've now realized that you aren't clear on whether or not you are using MVC routing or Angular routing. You mention angularjs in the tag, but then mention a Razor layout page. I think you need to clarify. – Brendan Green Jul 15 '15 at 04:21
  • I deleted the angularjs tag. In the title I clearly stated MVC. I could have included "using razor syntax" somewhere I suppose. I will check the solution purposed below. thanks – Rick Walker Jul 15 '15 at 16:13

1 Answers1

1

I've used this in the past.

Declare at the top of the layout:

@{
    var currentController = ViewContext.RouteData.Values["controller"] as string ?? string.Empty;
    var currentAction = ViewContext.RouteData.Values["action"] as string ?? string.Empty;

    string getImageSource(string basePath, string controller, string action)
    {
         var onOrOff = currentController.Equals(controller, StringComparison.OrdinalIgnoreCase) && currentAction.Equals(action, StringComparison.OrdinalIgnoreCase) ? "on.png" : "off.png";
         return string.Format("{0}_{1}", basePath, onOrOff);
    }
}

Then you can render the appropriate image based off the expected controller and action:

<div id="navbar">
    <div><a href="~/Home"><img src="@(getImageSource("~/Images/home", "Home", "Index"))" /></a></div>
    <div><a href="~/Home/Contact"><img src="@(getImageSource("~/Images/contact", "Home", "Contact"))" /></a></div>
</div>

I assume that the base ~/Home URL is going to the Index action on the HomeController, and that ~/Home/Contact is going to the Contact action on the HomeController.

Brendan Green
  • 11,676
  • 5
  • 44
  • 76