MVC Routing search page (hidden action, without a slash, such as SO)

I need my searches, for example, in stack overflow (i.e. no action, without a slash):

mydomain.com/search --> goes to a general search page mydomain.com/search?type=1&q=search+text --> goes to actual search results 

My routes:

 routes.MapRoute( "SearchResults", "Search/{*searchType}", --> what goes here??? new { action = "Results" } ); routes.MapRoute( "SearchIndex", "Search", new { action = "Index" } ); 

My SearchController has the following actions:

 public ActionResult Index() { ... } public ActionResult Results(int searchType, string searchText) { ... } 

The search results route does not work. I don’t want to use the "... / ..." approach, which everyone seems to use because the search query is not a resource, so I want the data in the query string, as I indicated, without slashes - exactly so same as SO.

TIA! Matt

+6
asp.net-mvc asp.net-mvc-routing
source share
1 answer

You do not need two routes, because you provide the search parameters as a query string. Only one search route:

 routes.MapRoute( "Search", "Search", new { controller = "Search", action = "Search" } ); 

Then write this controller action

 public ActionResult Search(int? type, string q) { var defaultType = type.HasValue ? type.Value : 1; if (string.IsNullOrEmpty(q)) { // perform search } // do other stuff } 

The body of this method depends heavily on the search condition, whether you need both parameters when searching for material or just q , and you have a default for type . Remember that page indexing can be done exactly the same.

Using strong type parameters (validation)

Of course, you can create a class that can be checked, but the property names should reflect the query string. So you will have a class:

 public class SearchTerms { public int? type { get; set; } public string q { get; set; } } 

And use the same query with the same query variables as you currently have, or have a clean class and adjust your query:

 public class SearchTerms { public int? Type { get; set; } public string Query { get; set; } } http://domain.com/Search?Type=1&Query=search+text 
+3
source share

All Articles