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

我有一个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} )

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....