【问题标题】:Checking equality of asp.net MVC generated urls检查 asp.net MVC 生成的 url 的相等性
【发布时间】:2017-10-27 07:19:25
【问题描述】:
@if (Url.Action() == Url.Action("index", "home")) {
<text>
   //some js code conditionally rendered.
   alert('test'); //Only should output, if current urls is home/index
</text>
}

我面临这个问题。对于默认路由,给定视图有多个 url。 例如请求时匹配的 home/index,

  1. / - 从默认值派生的控制器和动作。
  2. 主页/索引

我尝试使用 Url.Action() 来检查相等性。但检查的成功或失败取决于请求的 url。即当请求“\”(应用程序根)时,然后检查评估为真。当请求“home\index”时,检查结果为假。 Url.Action() 计算结果为“\”。

有没有更可靠的方法来检查当前视图 url 与一些带有默认路由的 mvc url?

【问题讨论】:

标签: asp.net-mvc asp.net-routing


【解决方案1】:

你应该直接检查路由数据而不是url,尤其是“controller”和“action”的值。

你会得到那些使用ViewContext.RouteData.Values["controller"]ViewContext.RouteData.Values["action"] 的人。然后,您可以确保控制器是“Home”并且操作是“Index”。

【讨论】:

    猜你喜欢
    • 2011-11-22
    • 2011-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-18
    • 1970-01-01
    相关资源
    最近更新 更多