简体   繁体   English

根据请求的视图更改href

[英]Change href based on requested view

I am trying to figure out how i can change links on a _layout.cshtml based on the requested view. 我试图弄清楚如何根据请求的视图更改_layout.cshtml上的链接。

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' 当我在首页/索引上时,我希望href为'#Unhealthy',但是在其他任何页面上时,我希望它重定向回首页'/ 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 *注意:我想如果我不能在服务器上执行此操作,则始终可以使用javascript / jquery更改值

use razor if your using MVC note i did this answer because you tagged MVC. 如果您使用的是MVC,请使用razor,因为我标记了MVC,所以我做了这个回答。 If you are doing a MVC application this is by far the best way it can be done, no need for any javascript. 如果您正在执行MVC应用程序,则这是迄今为止最好的方法,不需要任何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的方式做到这一点:

Jquery: jQuery:

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

html: 的HTML:

<li>
  <a id="Link" href="#"><i class="fa fa-warning warning"></i></a>
</li>
@{
    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>

The answer by Josh Stevens should work using MVC razor code but you could use same code on each page using @Html.ActionLink overloads 乔什·史蒂文斯(Josh Stevens)的答案应该可以使用MVC剃刀代码工作,但是可以使用@ Html.ActionLink重载在每个页面上使用相同的代码。

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) @ Html.ActionLink(“链接文本”,“索引”,“首页”,null,null,“不健康”,null,null)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM