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