Steven
Steven

Reputation: 18859

Custom route defaults to Index view

I have a view at /Folders/Index. I wanted to be able to navigate to /Folders instead, as well as pass an id, like /Folders/123. So I created this route:

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

This did work for the situations specified above.

The problem is that if I try to navigate to /Folders/Create, it just renders my Index view.

How can I change my route to work correctly?

I'm very new to the routing system, so apologies if this is a simple answer, but I thought this would do the trick. Also, could someone direct me to a good resource for learning how to do these on my own?

Upvotes: 0

Views: 66

Answers (2)

Yevgeniy.Chernobrivets
Yevgeniy.Chernobrivets

Reputation: 3194

I think you need to use two routes to resolve this situation - first to match "/Folders/Id" and second to resolve "/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"});

EDIT: If you want to map any parentFolderId parameter without constraint then you should first map create action and then 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 });

Upvotes: 2

Dmytro Rudenko
Dmytro Rudenko

Reputation: 2524

Try

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

Upvotes: 0

Related Questions