Passing arguments to an ASP.NET MVC5 controller

In our controller we might have a method along the lines

public string Search(string criteria, bool ignoreCase = true)
{
   // do something useful
   return $"Criteria: {criteria}, Ignore Case: {ignoreCase}";
}

Note: I’ve not bothered using HttpUtility.HtmlEncode on the return string as I want to minimize the code for these snippets.

So we can simply create a query string as per

http://localhost:58277/Music/Search?criteria=something&ignoreCase=false

or we can add/change the routing in RouteConfig, so for example in RouteConfig, RegisterRoutes we add

routes.MapRoute(
   name: "Music",
   url: "{controller}/{action}/{criteria}/{ignoreCase}"
);

now we can compose a URL thus

http://localhost:58277/Music/Search/something/false

Note: the routing names /{criteria}/{ignoreCase} must have the same names as the method parameters.

Obviously this example is a little contrived as we probably wouldn’t want to create a route for such a specific method signature.

We might simply incorporate partial parameters into the routine, for example maybe all our MusicController methods took a citeria argument then we might use

routes.MapRoute(
   name: "Music",
   url: "{controller}/{action}/{criteria}"
);

Note: there cannot be another route with the same number of parameters in the url preceding this or it will not be used.

and hence our URL would like like

http://localhost:58277/Music/Search/something?ignoreCase=false