Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make ASP.NET Routing escape route values?

I have an ASP.NET MVC site where I want routes like /{controller}/{id}/{action}/{date}, where "date" is the mm/dd/yyyy portion of a date/time. (I'm dealing with time-dimensioned data, so I need both an ID and a point in time to do most operations)

The route for this is simple:

routes.MapRoute(
    "TimeDimensionedRoute",
    "{controller}/{id}/{action}/{date}",
    new { controller = "Iteration", action = "Index", id = String.Empty, date = String.Empty }
);

This route correctly maps "/Foo/100/Edit/01%2F21%2F2010" to the desired action. Update: this is incorrect. This is NOT routed correctly, I was mistaken. See the related question linked in the accepted answer.

My problem is that when I use Html.ActionLink() to generate a link for this route, it does not URL-encode the date and I end up with invalid URLs such as "/Foo/100/Edit/01/21/2010".

Is there any way to get the routing infrastructure to encode the values for me? It seems wrong that I have to manually URL-encode data that I pass to the HTML helpers.

like image 421
Seth Petry-Johnson Avatar asked Feb 01 '10 03:02

Seth Petry-Johnson


2 Answers

I'm guessing that it doesn't automatically url encode it b/c its hard for the html helper to determine if you want to represent a date or if you want to have 3 more fields in the route e.g.

// Here's what you're seeing
/Foo  /100  /Edit  /10/21/2010/
// 4 route values

// But there's know way to know you don't want this
/Foo  /100  /Edit  /10  /21  /2010/
// 6 route values

Maybe you could change your route to be

...
"{controller}/{id}/{action}/{month}/{day}/{year}",
...

That way, it would always work without escaping.

Otherwise, you could do a URL Encoding of the date within the Html.ActionLink(...) call

like image 113
TJB Avatar answered Nov 15 '22 05:11

TJB


I don't know if this counts as an answer or not, but I always use yyyy-mm-dd format in URIs. Not because slashes are reserved per the RFC (although that's a good reason) but because it is immune to globalization issues when converting to/from a string. DateTime.Parse() "just works" with this format, even if someone sets the server locale to somewhere in Eastern Europe.

like image 21
Craig Stuntz Avatar answered Nov 15 '22 06:11

Craig Stuntz