asp.net-mvc URL.Action() 包括路由值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19107061/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
URL.Action() including route values
提问by hjavaher
I have an ASP.Net MVC 4 app and am using the Url.Action helper like this: @Url.Action("Information", "Admin")
我有一个 ASP.Net MVC 4 应用程序,并且正在使用这样的 Url.Action 助手: @Url.Action("Information", "Admin")
This page is used for both adding a new and edit an admin profile. The URLs are as follows:
此页面用于添加新的和编辑管理员配置文件。网址如下:
Adding a new: http://localhost:4935/Admin/Information
Editing Existing: http://localhost:4935/Admin/Information/5 <==Admin ID
When I'm in the Editing Existingsection of the site and decide that I would like to add a new admin I click on the following link:
当我在Editing Existing站点的部分并决定要添加新管理员时,我单击以下链接:
<a href="@Url.Action("Information", "Admin")">Add an Admin</a>
The problem however that the above link is actually going to http://localhost:4935/Admin/Information/5. This only happens when I'm in that page editing an existing admin. Anywhere else on the site it links correctly to http://localhost:4935/Admin/Information
然而,上面的链接实际上是要解决的问题http://localhost:4935/Admin/Information/5。只有当我在该页面中编辑现有管理员时才会发生这种情况。它正确链接到网站上的任何其他地方http://localhost:4935/Admin/Information
Has anyone else seen this?
有没有其他人看到这个?
UPDATE:
更新:
RouteConfig:
路由配置:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
回答by Emad Feiz
outgoing url in mvc generated based on the current routing schema.
基于当前路由模式生成的 mvc 中的传出 url。
because your Information action method require id parameter, and your route collection has id of your current requested url(/Admin/Information/5), id parameter automatically gotten from existing route collection values.
因为您的 Information 操作方法需要 id 参数,并且您的路由集合具有您当前请求的 url(/Admin/Information/5) 的 id,所以 id 参数会自动从现有的路由集合值中获取。
to solve this problem you should use UrlParameter.Optional:
要解决此问题,您应该使用 UrlParameter.Optional:
<a href="@Url.Action("Information", "Admin", new { id = UrlParameter.Optional })">Add an Admin</a>
回答by SSadig
You also can use in this form:
您也可以以这种形式使用:
<a href="@Url.Action("Information", "Admin", null)"> Admin</a>
<a href="@Url.Action("Information", "Admin", null)"> Admin</a>

