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

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, C

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

本文来自网络,不代表云浮站长网立场。转载请注明出处: https://www.0766zz.com/html/kaifa/asp-net/20200901/8584.html
上一篇
下一篇

作者: dawei

【声明】:云浮站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。

为您推荐

返回顶部