MVC3 Route Data Token Names

I learned about MVC 3, and I could not understand one aspect of routing.

If I have a route, for example below:

routes.MapRoute("Default", "{controller}/{action}/{ID}"); 

The route restricts each action to only one name identifier parameter! Although there are no restrictions on the name of the controller or action for this route.

Of course, I could define more routes, but there should be a better way for the route to accept data tokens such as ListID or FieldID.

For example: I have a ListController with two actions:

 GetListByID(int listID) and GetFieldByID(int fieldID) 

In this case, I have to define two routes, because the function parameter name is different. Is there a better way to do this? Thanks!

+4
source share
3 answers

No, your actions can take any number of parameters, but only that one parameter in your action with the name "ID" will contain the value of what is in the URL at this position represented by {ID}

If you have this action in CartController

 public ActionResult Add(int ID, int quantity) { /* method body */ } 

URL

 /cart/add/1234 

will call the CartController Add method, passing in 1234, with the ID parameter and zero in quantity

but

 /cart/add/1234?quantity=4 

set quantity as 4

You can also have complex arguments. Here is a good introduction. Http://weblogs.asp.net/scottgu/archive/2007/12/03/asp-net-mvc-framework-part-2-url-routing.aspx

+3
source

If you do not specify more routes, your data tokens will be displayed as

 /YourController/YourAction/3?ListID=123&FieldID=456 

If you need something smaller tokeny like

 /YourController/YourAction/3/123/456 

you need to define the route as

 routes.MapRoute("TokenHostileRoute", "{controller}/{action}/{ID}/{ListID}/{FieldID}"); 
+2
source

The only requirement is that the parameter name must match the token name. You can use any marker name you want. controller and action are reserved names.

+1
source

Source: https://habr.com/ru/post/1345499/


All Articles