Reputation:
I am trying to do what SO does for its Question controller.
/Posts/{id}/{title}
when viewing a post (action name not shown) /Posts/New
when you are posting something new. /Posts/Delete/10
etc....I have two routes set up (well, one if you don't count the default). What appears to be happening is all actions in the Post controller are being routed through the first one.
What is that? I obviously have it wrong, but I can't figure this out.
routes.MapRoute("ViewPosts",
"Posts/{postid}/{title}",
new { controller = "Posts", action = "View", postid = "", title = "" });
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
Upvotes: 1
Views: 93
Reputation: 30095
The first route handles all your requests which starts from /Posts
.
You need to use constraints to allow {postid}
be only number:
routes.MapRoute("ViewPosts",
"Posts/{postid}/{title}",
new { controller = "Posts", action = "View", postid = "", title = "" },
new { postid= @"\d+" });
In this case only if numeric Id is provided this route will handle it, otherwise "Default" route will handle.
Upvotes: 1
Reputation: 40149
All routes are going through the first because you have not specified that the postid
field can only be numeric, or defined an earlier route that will catch /Posts/New
. It is passing New
as the postid
with the View
action.
You can add this route definition before the ones you have now:
routes.MapRoute("NewPost",
"Posts/New",
new{controller="Posts", action="New"});
Or whatever the appropriate controller/action would be.
Upvotes: 1