7

I have this application, and the default date format must be dd/MM/yyyy (the language is Brazilian Portuguese).

I already had set culture and UI culture to pt-BR and now myDate.ToShortDateString() returns the dates as I want. I have no trouble displaying them.

The problem is, when the user fills an input field with a date such as 17/08/2011 and submits the form the DateTime parameter to my action becomes null. If I supply a date in the format 08/17/2011, it works fine.

How can I make the ASP.Net MVC model binding to parse my dates correctly?

Doug
  • 6,322
  • 3
  • 29
  • 48
  • 4
    check this answer http://stackoverflow.com/questions/528545/mvc-datetime-binding-with-incorrect-date-format/528560#528560 – dotjoe Aug 17 '11 at 20:00
  • Try the solution from this question http://stackoverflow.com/questions/6177626/asp-net-mvc-default-model-binder-problem – agradl Aug 17 '11 at 20:01

3 Answers3

11

I found what happended. My form was posting via GET method, and the MVC just uses the culture for an action parameter when it's passed in the RouteData or by the form via POST method.

I just changed the form to POST method and it worked.

Doug
  • 6,322
  • 3
  • 29
  • 48
  • A day lost just because noone ever say that the GET method doesn´t apply the culture. Saved my day.. Thanks, still, you should correct your post, it works with POST not with GET. – Phoenix_uy Oct 21 '11 at 21:32
  • More info about how the MVC ModelBinder works and why: http://weblogs.asp.net/melvynharbour/mvc-modelbinder-and-localization – webStuff Aug 05 '16 at 07:19
5

Try this on your property in the view model:

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
Tae-Sung Shin
  • 20,215
  • 33
  • 138
  • 240
1

I'm pretty sure the issue is a lack of a DateTimeFormat on your DateTime types.

<input type="text" name="DateProperty" id="DateProperty"
       value="@(Model.DateProperty.Value.ToString("d",
             System.Threading.Thread.CurrentThread.CurrentUICulture.DateTimeFormat))" />

EDIT**

Another thing you want to be sure of is that the "name" property of your input element matches what you're passing into your action. If it doesn't null will appear on POST action every time.

     [HttpPost]
     public ActionResult DoStuff(string dateParam)
     {
       return RedirectToAction("Home","Index", new { });
     }

"dateParam" Should match the name property here.

<input id="dateParam" name="dateParam" value="10/10/2010" />
Scoregraphic
  • 7,110
  • 4
  • 42
  • 64
The Internet
  • 7,959
  • 10
  • 54
  • 89
  • Outputting the date to HTML is not the problem. Binding the submitted value is. Even if I do what you said the form submit will not work as expected. – Doug Aug 17 '11 at 20:09