Reputation: 91
In my ASP MVC web application, my controllers often have action with a "name" parameter, like this:
Function Consult(name As String) As ActionResult
.....
Return View()
End Function
I would like to be able to browse these actions the same way I would browse them with an "id" parameter: ../Book/Consult/MyBookName
But I want the default route to continue to work with "id" parameters. In other words, I would like the default route to accept either "id" or "name" as parameter name.
So I tried to configure my routes like this but it does not work as all the requests seems to use the first route and never the second. Actions with "id" parameters do not work anymore.
routes.MapRoute( _
name:="Name", _
url:="{controller}/{action}/{name}", _
defaults:=New With {.controller = "Home", .action = "Index", .id = UrlParameter.Optional} _
)
//Default Route
routes.MapRoute( _
name:="Default", _
url:="{controller}/{action}/{id}", _
defaults:=New With {.controller = "Home", .action = "Index", .id = UrlParameter.Optional} _
)
My code examples are in VB but I will accept answers in C# as well :) Thanks a lot folks.
EDIT: To clarify,if I simply rename the parameter to "id", everything works fine with just the default route in my route config. But I would like to keep "name" as it is way more clean in these specific cases..
Upvotes: 3
Views: 4243
Reputation: 3342
I believe your problem is in the defaults:
routes.MapRoute( _
name:="Name", _
url:="{controller}/{action}/{name}", _
defaults:=New With {.controller = "Home", .action = "Index", .id = UrlParameter.Optional} _
)
.id should match your parameter name so try:
routes.MapRoute( _
name:="Name", _
url:="{controller}/{action}/{name}", _
defaults:=New With {.controller = "Home", .action = "Index", .name = UrlParameter.Optional} _
)
Upvotes: 0
Reputation: 596
Try using a route constraint.
http://msdn.microsoft.com/en-us/library/cc668201(v=vs.100).aspx#adding_constraints_to_routes
routes.MapRoute(
"Name",
"{controller}/{action}/{name}",
new { controller = "Home", action = "Index", id = "" },
new RouteValueDictionary
{{"name", "[a-zA-Z]*"}}
);
This should restrict the route to names that contain only letters. If the name can contain numbers, adjust the regular expression accordingly.
Upvotes: 4