Tigraine

Daniel Hoelbling-Inzko talks about programming

DateTime parsing in ASP.NET MVC RouteEngine

Posted by Daniel Hölbling on January 15, 2009

After doing so much winforms development lately I am getting started on an upcoming an MVC project. And while thinking about the basic structure of the whole thing and trying out some things I discovered some pretty funny behavior in the DateTime parsing of the routing engine.

Typical example. A route that should map urls like:

http://www.website.com/Archive/10-12-2008/

I have my route laid out like this:

routes.MapRoute("Archive",
                "Archive/{date}/",
                new {controller = "Archive", action = "Show"});

And the controller action looks like this:

public class ArchiveController : Controller     
{
    public ActionResult Show(DateTime date)
    {
        return View();
    }
}

Now, when I open the browser and point it to the following URL it works

http://localhost:51942/Archive/12.12.2008

While this one doesn’t

http://localhost:51942/Archive/15.11.2009

The second one returns the following error:

The parameters dictionary does not contain a valid value of type 'System.DateTime' for parameter 'date' which is required for method 'System.Web.Mvc.ActionResult Show(System.DateTime)' in 'MVCDateTimeParseTest.Controllers.ArchiveController'. To make a parameter optional its type should either be a reference type or a Nullable type.

 

Needless to say that I am a bit lost at the moment. Both are perfectly valid dates and yet one works the other doesnt. I had the same problem when trying other formattings when I tried dd-MM-yyyy. Why and when dates get parsed correctly is very random it seems.

I didn’t constrain the route on purpose to test out how to create links with dates in them (and doing a 2008/11/12 style link also doesn’t really work too well). The only formatting that seems to be working 100% of the time is http://localhost:51942/Archive/2009-12-12. And that’s not really how I (Austria formats dd.MM.yyyy) like it.

Any suggestions?

Filed under net, programmierung
comments powered by Disqus

My Photography business

Projects

dynamic css for .NET

Archives

more