Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending ?param= to mvc routes

Some MVC sites have querystring params appended to the route Url (of which I noticed StackOverflow does), such as:

https://stackoverflow.com/questions/tagged/java?page=9802&sort=newest&pagesize=15

What are the advantages of having the parameters as more conventional ?querystring params, rather than /param/values/ ?

Also, how are these params appended to routes that have been set up? I'm familiar with setting up mvc routes with params like "users/details/{id}" etc. but don't know how to configure routes for use with 1 or more ?params as per the example url above?

like image 993
Marc Avatar asked Aug 09 '11 11:08

Marc


1 Answers

Query string parameters are useful when you have multiple optional parameters and don't want to include default values for non-specified parameters just to satisfy a path.

And you don't have to do anything special to include these parameters in a rendered URL.

Take the following route for example:

routes.MapRoute
(
    "QuestionsTagged",
    "questions/tagged/{tag}",
    new { controller = "Questions", action = "Tagged" }
);

If you render a link to that route using:

Url.RouteUrl
(
    "QuestionsTagged",
    new
    {
        tag = "java",
        page = 9802,
        sort = "newest",
        pagesize = 15
    }
 )

...then the routing engine is smart enough to see that the route contains a parameter named tag and that the passed route values object also has something named tag so it uses that value in the route.

Any provided route values that don't have corresponding parameters in the route (page, sort and pagesize in this case) get tacked on as query string parameters. So the Url.RouteUrl call above would return /questions/tagged/java?page=9802&sort=newest&pagesize=15.

And your action method can explicitly list these parameters in its signature (promotes readability and maintainability) or you can access them via 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();
    }
}

Note that the parameters to the action method do not have to match the parameters specified in the route. (In the route, I only specified tag, but the action method's signature lists tag, page, and pagesize.) However, any parameter of the action method that is not also a parameter of the route must be a reference or nullable type.

like image 93
Lobstrosity Avatar answered Sep 28 '22 12:09

Lobstrosity