Why would this route result in 404 Not Found when hitting url /users/3 to call upon the route with a page number only in ASP.NET MVC:
routes.MapRoute(
"Users", // Route name
"users/{page}/{sortColumn}/{sortDirection}", // URL with parameters
new { controller = "User", action = "Index", page = UrlParameter.Optional, sortColumn = UrlParameter.Optional, sortDirection = UrlParameter.Optional }, // Parameter defaults
new { page = @"\d+", sortColumn = @"[\w-]+", sortDirection = @"asc|desc" } // Route constraints
);
Shouldn’t it be okay for me to load the route simply with the page parameter specified, as the sortColumn and sortDirection parameters are both set to UrlParameter.Optional?
Update:
Ok after digging up another StackOverflow answer on a similar topic, it appears if you choose to have an optional route, the constraint must also be optional. So changing my route constraints to:
new { page = @"\d*", sortColumn = @"[\w-]*", sortDirection = @"(asc|desc)?" }
which simply tests for zero or more matches makes my pages load up on all accounts.
However, if I try to make a route link that reflects that (@Html.RouteLink("test 2", "Users", new { page = 2 })), the hyperlink is generated as /users not /users/2! Strange thing though, if I manually hit /users/2 then the RouteLink is written as /users/2 lol Argh! 🙂
Perhaps I do have to make separate routes, but this is really not desirable as I don’t want to have to call upon differently named routes in Html.RouteLink()….
Thoughts?
Because you provide two parameters, but it expects 3 optional ones.. so it does not know which one is missing …
In general you cannot use two consecutive optional parameters.
References