Query string parameters are useful when you have several optional parameters, and do not want to include default values ββfor parameters not specified just to satisfy the path.
And you donβt have to do anything special to include these parameters in the display URL.
Take the following route, for example:
routes.MapRoute ( "QuestionsTagged", "questions/tagged/{tag}", new { controller = "Questions", action = "Tagged" } );
If you pass a link to this route using:
Url.RouteUrl ( "QuestionsTagged", new { tag = "java", page = 9802, sort = "newest", pagesize = 15 } )
... then the routing mechanism is smart enough to see that the route contains a parameter named tag and that the object of the transferred route objects also has something called tag , so it uses this value in the route.
Any provided route values ββthat do not have corresponding parameters in the route ( page , sort and pagesize in this case) are inserted as query string parameters. So calling Url.RouteUrl above would return /questions/tagged/java?page=9802&sort=newest&pagesize=15 .
And your action method can explicitly list these parameters in its signature (improves readability and maintainability), or you can access them through Request.QueryString .
public class QuestionsController : Controller { // I can explicitly list the parameters in my signature and let routing do // its magic, like this... public ViewResult Tagged(string tag, int? page, int? pagesize) { // ...or I can grab parameters like this: string sort = Request.QueryString["sort"]; return View(); } }
Please note that the parameters of the action method must not match the parameters specified in the route. (In the route, I specified only tag , but in the list of signature of the action method tag , page and pagesize .) However, any parameter of the action method, which is also not a parameter of the route, must be a reference or null type.