0

I am trying to figure out how i can change links on a _layout.cshtml based on the requested view.

When I am on the Home/Index I want the href to be '#Unhealthy' but when im on any other page, I want it to redirect back to the home page '/Home/Index/#Unhealthy'

When on other page

<li>
  <a href="/Home/Index/#Unhealthy"><i class="fa fa-warning warning"></i></a>
</li>

When on Home/Index

<li>
  <a href="#Unhealthy"><i class="fa fa-warning warning"></i></a>
</li>

How can I determine the requested view to swap this value?

*Note: I suppose if I cant do it at the server I can always change the values with javascript/jquery

Zholen
  • 1,762
  • 2
  • 24
  • 53

3 Answers3

2

use razor if your using MVC note i did this answer because you tagged MVC. If you are doing a MVC application this is by far the best way it can be done, no need for any javascript.

@if (window.location.pathname == "/"){
<li>
  <a href="#Unhealthy"><i class="fa fa-warning warning"></i></a>
</li>
}
else{
<li>
  <a href="/Home/Index/#Unhealthy"><i class="fa fa-warning warning"></i></a>
</li>
}

if you did want to do it the jQuery way this would work:

Jquery:

$( document ).ready(function() {   
  if (window.location.pathname == "/"){ 
   $("#Link").prop("href", "#Unhealthy")
  }
  else {
    $("#Link").prop("href", "/Home/Index/#Unhealthy")
  }
});

html:

<li>
  <a id="Link" href="#"><i class="fa fa-warning warning"></i></a>
</li>
Josh Stevens
  • 3,943
  • 1
  • 15
  • 22
1
@{
    var controller = ViewContext.RouteData.Values["controller"].ToString().ToLower();
    var action = ViewContext.RouteData.Values["action"].ToString().ToLower();
}

<li><a href="@(controller == "home" && action == "index" ? "#Unhealthy" : "/Home/Index/#Unhealthy")"><i class="fa fa-warning warning"></i></a></li>
user2436996
  • 181
  • 2
  • 9
0

The answer by Josh Stevens should work using MVC razor code but you could use same code on each page using @Html.ActionLink overloads

A quick search finds this link that is old syntax but concept correct

Without Testing try

@Html.ActionLink("Link Text", "Index", "Home", null, null, "Unhealthy", null, null)

Community
  • 1
  • 1
ShufflerShark
  • 377
  • 1
  • 4
  • 20