user60456
user60456

Reputation:

Why is the wrong route being used?

I am trying to do what SO does for its Question controller.

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

Answers (2)

Samich
Samich

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

Andrew Barber
Andrew Barber

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

Related Questions