Reputation: 4528
If I have a controller like this...
Public Function GetData(fromDate As Date, toDate As Date) As ActionResult
then my url has to be english (MM-DD-YYYY) like ...
.../GetData?fromDate=2-27-2014&toDate=9-29-2014
But since all my users are danish (DD-MM-YYYY), this will not work...
.../GetData?fromDate=27-2-2014&toDate=29-2-2014
Can I tell MVC to expect danish (DD-MM-YYYY) arguments or do I have to translate the date to MM-DD-YYYY on the client before sending it to the server?
Upvotes: 2
Views: 176
Reputation: 4594
MVC model binding takes into account Current Culture (locale). For example, your users are using da-DK
culture and your application (server) is set to en-US
culture. So obviously the date formats would be different between the two cultures.
One easy option for this is in your Web.config
under <system.web>
set
<globalization culture="da-DK" uiCulture="da-DK" />
This globally configures your application to use da-DK
culture. This way your controller action knows to expect the dates in dd-MM-yyyy
format.
Scott Hanselman has a nice article on this topic: Globalization, Internationalization and Localization ...
UPDATE
This answer is only valid for the POSTed data, however in MVC the query string is parsed using InvariantCulture
. The InvariantCulture
's ShortDatePattern
is MM/dd/yyyy
.
For example, the following query string parameters would all parse as January 7, 2014: 01/07/2014
, 01-07-2014
, 01.07.2014
.
Also, the following would also parse as January 7, 2014: 2014/01/07
, 2014-01-07
, 2014.01.07
.
This last example aligns with the ISO international date format and this format should be used for query string parameters.
Upvotes: 1
Reputation: 423
If you use the ISO 8601 date format, then your bindings will work for any locale.
In VB.Net you can use the string format .ToString("s")
to create the parameters for your URL.
In JavaScript you can use the .toISOString()
function to create the parameters for your URL.
The ISO 8601 date format will bind to a DateTimeOffset parameter in your controller:
Public Function GetData(fromDate As DateTimeOffset, toDate As DateTimeOffset) As ActionResult
Upvotes: 2