Sasha
Sasha

Reputation: 20854

Looks like binder for date works incorrect in asp.net mvc

enter image description here

I have startdate in QueryString with value: 3/1/2012

DateTime.Parse(Request.QueryString["startdate"]).Month return month number: 1

but in my controller i have action Index(DateTime startDate) and startDate.Month return 3

Is anybody can explain why bind of date doesnt work as expected?

btw, i have culture in web.config already:

<globalization uiCulture="en-GB" culture="en-GB"/>

Upvotes: 4

Views: 2658

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039548

The default model binder always uses InvarianCulture when parsing query string values, no matter which culture you configured in your web.config.

  • GET => InvariantCulture
  • POST => culture agnostic

So assuming you have the 2 actions:

[HttpGet]
public ActionResult Foo(DateTime date)
{
    ...
}

[HttpPost]
public ActionResult Bar(DateTime date)
{
    ...
}

when you invoke the Foo action you should always use the invariant culture to format the date in the query string, whereas when you invoke the Bar action and pass the date parameter in the POST body payload, the default model binder will use the culture configured in your web.config.

Take a look at the following blog post which covers this in more details.

Upvotes: 7

Related Questions