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"/>

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x