加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc-3 – Url.Action没有给出预期的结果.不需要的路线值

发布时间:2020-12-15 20:57:53 所属栏目:asp.Net 来源:网络整理
导读:我有一个MVC3应用程序与几个路线.其中两个定义如下: routes.MapRoute( null,"System/{name}",// URL with parameters new { controller = "Systems",action = "Index" } // Parameter defaults);routes.MapRoute( null,"Carrier/{name}",// URL with parame
我有一个MVC3应用程序与几个路线.其中两个定义如下:
routes.MapRoute(
  null,"System/{name}",// URL with parameters
  new { controller = "Systems",action = "Index" } // Parameter defaults
);
routes.MapRoute(
  null,"Carrier/{name}",// URL with parameters
  new { controller = "Carriers",action = "Index" } // Parameter defaults
);

现在,在我的菜单中,我有两个指向使用Url.Action创建的路径的链接:

Url.Action("Index","Systems")
Url.Action("Index","Carriers")

现在,当我启动应用程序时,一切似乎都很好,菜单中的链接显示为/ System /和/ Carrier /,这是预期的值.

但是,当我在网页中浏览例如/ System / MySystem时,我仍然希望链接指向同一个地方,但现在他们指向/ System / MySystem和/ Carrier / MySystem.

我已经尝试了很多东西来保持链接不使用路由值中的名称,但无济于事.我遇到的最奇怪的情况是我试过这个:

Url.Action("Index","Systems",new{name = (string)null})

现在链接显示为

/System?name=MySystem

有没有什么好方法可以确保路由值中的名称值不会以任何方式干扰这些链接?

解决方法

你注意到了Url.帮助程序重用先前给定的路由参数.

作为一种解决方法(我希望有一个更优雅的解决方案……),您可以从视图中的RouteData.Values中删除名称条目:

所以在你的视图中给你调用Url.Action之前:

Url.Action("Index","Carriers")

从RequestContext中删除预填充名称:

@{
     Request.RequestContext.RouteData.Values.Remove("name");
}

这也是一种解决方法,但如果您通过为您的名称段提供默认空值来稍微修改您的路线:

routes.MapRoute(
  null,action = "Index",name = (string)null }
);
routes.MapRoute(
  null,name = (string)null }
);

您的原始解决方案(“归零”Url.Action中的名称)也将起作用:

@Url.Action("Index",new {name = (string)null} )

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读