Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC: url routing vs querystring

I have a page routed like /Comments/Search/3 where i search and display all the comments of the thread "3".

I'm adding a sort function (by date, author etc). What is the best way to handle it? /Comments/Search/3/Sort/Author or /Comments/Search/3?sort=author ?

How do I automatically handle the querystring sort=author as a parameter in MVC?

Thanks

like image 610
pistacchio Avatar asked Jun 09 '09 08:06

pistacchio


People also ask

What is a QueryString used for?

A querystring is a set of characters input to a computer or Web browser and sent to a query program to recover specific information from a database .

What is URL Routing in MVC?

Routing enables us to define a URL pattern that maps to the request handler. This request handler can be a file or class. In ASP.NET Webform application, request handler is . aspx file, and in MVC, it is the Controller class and Action method.

What is QueryString in MVC?

Generally, the query string is one of client-side state management techniques in ASP.NET in which query string stores values in URL that are visible to Users. We mostly use query strings to pass data from one page to another page in asp.net mvc. In asp.net mvc routing has support for query strings in RouteConfig.

What is request QueryString ()?

The value of Request. QueryString(parameter) is an array of all of the values of parameter that occur in QUERY_STRING. You can determine the number of values of a parameter by calling Request. QueryString(parameter).


1 Answers

I prefer: /Comments/Search/3?sort=author. The querystring is a good place to pass in programmatic parameters, especially if the parameter (like in this case) is not important for SEO purposes. If the parameter had some semantic meaning as a search term, the first URL would be better.

In a controller method you can use something like this:

public ActionResult Search(int id, string sort) 

ASP.NET MVC will automatically wire up querystring values to the parameters of your method.

Use the following route

routes.MapRoute(                    "Default",                                              // Route name                    "{controller}/{action}/{id}",                           // URL with parameters                    new { controller = "Comments", action = "Search", id = "" }  // Parameter defaults                ); 

/Comments/Search/3?sort=author will call Search(3, "author")

/Comments/Search/3 will call Search(3, null)

Keep in mind that id is mandatory so this url will fail: /Comments/Search

like image 81
Praveen Angyan Avatar answered Sep 22 '22 17:09

Praveen Angyan