RouteValues vs QueryString MVC?

2019-04-26 20:44发布

问题:

Whats the differences between QueryString in Request and RouteData.Values ?
Can we use them instead ?

回答1:

RouteValues are gathered from querystring only if are defined in global.asax, for example:

routes.MapRoute(
 "Example", // Route name
 "{controller}/{action}/{id}/{inRouteValues}", // URL with parameters
 new { controller = "Home", action = "Index" } // Parameter defaults
 );

will catch inRouteValues from yourdomain/testController/testAction/14/myTestValue where RouteData.Values["inRouteValues"] will be string with value "myTestValue".
But if you will build URL like yourdomain/testController/testAction/14?inRouteValues=myTestValue it won't get it. So difference is that RouteData.Values will get only values from URLs that match RouteCollectionfrom your global.asax and QueryString will catch every value from your querystring if it matches variable name.