42

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

3 Answers 3

59

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

Sign up to request clarification or add additional context in comments.

3 Comments

I think I'd go for this solution. How do I route it and set a default, as the sort=3 is optional?
Because of the convention over configuration, keep in mind that your parameters for your method MUST be called 'id' and 'sort' respectively.
In MVC 2 you can use UrlParameter.Optional and in action parameter use int? id instead of int id if you want it to be optional and /Comments/Search to show the default search UI with empty input text.
20

ASP.NET MVC will handle that automatically in the query string case. You just add a string sort parameter to your action.

Which is better? Personally, I use the path to control the contents being displayed and querystring to control the presentation (how it's displayed, formatted, ...). So, for sorting, I'd go with the querystring method. But I don't think there's a technical disadvantage in either approach.

Comments

2

Your best bet is to add a routing rule to handle it. There's a handy article on it here:

http://aspalliance.com/1525_ASPNET_MVC_Framework_Part_2_URL_Routing.2

Then your URL would read /Comments/Search/3/Sort/Author

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.