views:

201

answers:

3

I currently have a collection of routes like

{controller}/{action}/{from}/{to}/{some}/{other}/{things}
{controller}/{action}/{from}/{to}/{some}/{other}
{controller}/{action}/{from}/{to}
{controller}/{action}

and views with forms with get actions to retrieve the results. But the get actions go to the default/last route with the parameters in the query strings. What's the best approach to handle redirecting to the pretty-url for the most specific route? i.e. when the form submits goes to myurl.com/controller/action?from=20091021&to=20091131 its redirected to myurl.com/controller/action/from-20091021/to-20091131

Generally, I'm wondering if I'm just missing something fundamental about sensible route design, as I'm also having a little trouble with Html.RouteLink mapping to a route rather than the query string style urls.

Thanks in advance for any advice/ guidance/ useful links.

+2  A: 

A form is always going to encode the parameters as a query string. If you want the client to issue a pretty url GET, then you'll want to go with a submit handler than constructs the URL on the client side. If it's okay to have an extra round trip, then consider using a POST and have an action which takes the POST and reconstructs the url and does a RedirectToAction to an action that accepts the values via GET.

Client-side:

 $(function() {
     $('form').submit( function() {
         var params = [ $('from').val(), $('to').val(), ... ];
         location.href = $(this).attr('action') + '/' + params.join('/');
         return false;
     });
 $);

Server-side

 [AcceptVerbs( HttpVerbs.Post )]
 [ActionName( "MyAction" )]
 public ActionResult MyPostAction( string from, string to, ... )
 {
     // you may be able to simply reuse the RouteValueDictionary, but may
     // also need some transformations...
     return RedirectToAction( "MyAction", new { from = from, to = to, ... } );
 }

 [AcceptVerbs( HttpVerbs.Get )]
 public ActionResult MyAction( string from, string to, ... )
 {
     ...
 }
tvanfosson
A: 

Thanks, I'm fine with the GET, and the query string, I'd just like to have the prettier URLs where possible.

So you'd have one additional action per action, rather than one centralised Redirect action? I've tried having a hidden form item rediraction which I then use as the actual action I want in RedirectToAction, but that wasn't getting populated.

lbp
A: 

Aha! I think I've found my problem with route-based stuff not returning the route I was expecting - I had specified defaults for too many of the routes, and this then meant the default (last) route was always matching - and every parameter ended up in the querystring.

Lbp