Here is my scenario. For the example lets say that I need to return a list of cars based on a search criteria. I would like to have a single View to display the results since the output will be the same, but I need several ways of getting there. For instance, I may have a Form with a textbox to search by year. I may have another separate page that contains a hyperlink for all red, Toyota cars. How do I handle these multiple scenarios in the same View and Controller. My dilemma is that the search could contain several options… year, make, model, etc but I don’t know where to put them.
What is the best approach for this? Should I define the parameters in the routing or go with query strings, etc?
Option 1
Of course you always can choose the way of /car/search/?vendor=Toyota&color=Red&model=Corola and I think it will be good for you.
You can get params from Request.Params in action in this case.
Option 2
Or you can define params in the routing table, but AFAIK it will be required to make a set of rules for all possible combinations, because an order of the params matter, for example:
… an so on. It’s true if you are going with the standard MvcRouteHandler.
But it was an easy ways 🙂
Option 3
The hard, but, I think, most elegant way, is to make your own IRouteHandler implementation – it will give you much more flexibility in params order. But again, its a hard way, dont go with it if you have a simple app. So, just for example of how to make it this way (very simple example):
Add new route to the list of routes:
Add classes that will tweak the standard request processing chain:
In controller:
And it will work with any search parameters order:
But also dont forget to make a link generation logic, because Html.ActionLink and Html.RenderLink will not give you url in pretty form of /car/search/model/Corola/color/red/vendor/Toyota, so you’ll need to make a custom link generator.
So, if you need a really flexible routing – you’d better go with this hard way 🙂