Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 4 Routes - controller/id vs controller/action/id

Tags:

I'm trying to add a route to the default one, so that I have both urls working:

  1. http://www.mywebsite.com/users/create
  2. http://www.mywebsite.com/users/1

This will make the first route work:

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

However, the second route won't work obviously.

This will make the second route work, but will break the first one:

routes.MapRoute(      name: "Book",      url: "books/{id}",      defaults: new { controller = "users", action = "Details" } ); 

How to combine the two route configurations so that both URLs work? I apologize if there is already a question like this on SO, I wasn't able to find anything.

like image 305
Arman Bimatov Avatar asked Aug 03 '13 23:08

Arman Bimatov


People also ask

What is ASP route ID?

asp-route. The asp-route attribute is used for creating a URL linking directly to a named route. Using routing attributes, a route can be named as shown in the SpeakerController and used in its Evaluations action: C# Copy.

What is RouteConfig Cs in ASP.NET MVC?

In MVC, routing is a process of mapping the browser request to the controller action and return response back. Each MVC application has default routing for the default HomeController. We can set custom routing for newly created controller. The RouteConfig. cs file is used to set routing for the application.

What is the difference between Web API routing and MVC routing?

If you are familiar with ASP.NET MVC, Web API routing is very similar to MVC routing. The main difference is that Web API uses the HTTP verb, not the URI path, to select the action. You can also use MVC-style routing in Web API.


1 Answers

The key is to put more specific routes first. So put the "Book" route first. Edit I guess you also need a constraint to only allow numbers to match the "id" part of this route. End edit

routes.MapRoute(     name: "Book",     url: "books/{id}",     defaults: new { controller = "users", action = "Details" },     constraints: new { id = @"\d+" } );  routes.MapRoute(     name: "Default",     url: "{controller}/{action}/{id}",     defaults: new { controller = "users", action = "Index", id = UrlParameter.Optional } ); 

And ensure that the "id" parameter in your "Details" action is an int:

// "users" controller public ActionResult books(int id) {     // ... } 

This way, the "Books" route will not catch a URL like /users/create (since the second parameter is reqiured to be a number), and so will fall through to the next ("Default") route.

like image 153
McGarnagle Avatar answered Sep 20 '22 22:09

McGarnagle