Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a DateTime to controller via URL causing error in ASP .NET MVC 3 (culture)

Tags:

My application is setted with pt-BR culture (Date is dd-mm-yyyy) in web.config:

<globalization enableClientBasedCulture="false" requestEncoding="utf-8" responseEncoding="utf-8" fileEncoding="iso-8859-15" responseHeaderEncoding="utf-8" resourceProviderFactoryType="string" enableBestFitResponseEncoding="true" culture="pt-BR" uiCulture="pt-BR" /> 

All DateTime created on my system is in right format, but I created a controller method like that:

public ActionResult Test(DateTime date) { } 

Calling that method direct in the browser is passing null when the date is with portuguese-br format, like that:

mysite/Test/?date=19/01/2012   => date = null in my controller  mysite/Test/?date=01/01/2012   => date is fine, but in US format (mm-dd-yyyy) 

How can I fix that, to accept my date format?

like image 267
Paul Avatar asked Jan 18 '12 12:01

Paul


People also ask

How does MVC handle wrong URL?

If those URLs don't include a controller or action method name, then you can provide the missing information through default values on your routes. But if those URLs include an incorrect action or controller name, then ASP.NET MVC will simply return one of the standard HTTP error codes.

How do I pass date as query string?

string dateTime = Request. QueryString["DateStarted"]; DateTime dt = Convert. ToDateTime(dateTime); Response.


1 Answers

There's a gotcha with the default model binder that is not easy to know about but once you know it you no longer make the same mistake:

  • When you use a POST request, the default model binder uses your culture settings to parse the dates.

  • When you use a GET request, the default model binder uses CultureInfo.InvariantCulture to parse the dates and ignores your current culture settings.

Since you are using a GET request and passing the date as a query string parameter, you should format it using the invariant culture format when sending it in the url. The correct way to format your date as a query string parameter is yyyy-MM-dd.

You may take a look at the following blog post which gets into more details.

like image 52
Darin Dimitrov Avatar answered Sep 22 '22 09:09

Darin Dimitrov