自定义路由默认为“索引”视图

时间:2013-11-19 19:22:45

标签: asp.net asp.net-mvc asp.net-mvc-4 asp.net-mvc-routing

我在/Folders/Index有一个观点。我希望能够导航到/Folders,并传递ID,例如/Folders/123。所以我创建了这条路线:

routes.MapRoute(
    name: "",
    url: "Folders/{parentFolderId}",
    defaults: new { controller = "Folders", action = "Index",
        parentFolderId = UrlParameter.Optional }
);

这适用于上述情况。

问题是,如果我尝试导航到/Folders/Create,它只会呈现我的Index视图。

如何更改路线才能正常工作?

我对路由系统很新,所以如果这是一个简单的答案,请道歉,但我认为这样做会有所帮助。另外,有人可以指导我学习如何独立完成这些工作吗?

2 个答案:

答案 0 :(得分:2)

我认为您需要使用两条路线来解决这种情况 - 首先匹配“/ Folders / Id”,然后再解决“/ Folders / Action”

routes.MapRoute(
name: "",
url: "Folders/{parentFolderId}",
defaults: new { controller = "Folders", action = "Index",
    parentFolderId = UrlParameter.Optional },
constraints: new { parentFolderId = @"^[0-9]*$" });

routes.MapRoute(
name: "",
url: "Folders/{action}",
defaults: new { controller = "Folders", action = "Index"});

修改 如果要在没有约束的情况下映射任何parentFolderId参数,则应首先映射create action,然后映射parentFolderId。

routes.MapRoute(
name: "",
url: "Folders/Create",
defaults: new { controller = "Folders", action = "Create"});

routes.MapRoute(
name: "",
url: "Folders/{parentFolderId}",
defaults: new { controller = "Folders", action = "Index",
    parentFolderId = UrlParameter.Optional });

答案 1 :(得分:0)

尝试

routes.MapRoute(
    name: "",
    url: "Folders/{action}",
    defaults: new { controller = "Folders", action = "Index" }
);