How can I force the format of datetime in asp.net mvc 4 ?
In display mode it shows as I want but in edit model it doesn't.
I am using displayfor and editorfor and applyformatineditmode=true with dataformatstring="{0:dd/MM/yyyy}"
What I have tried:
- globalization in web.config (both of them) with my culture and uiculture.
- modifying the culture and uiculture in application_start()
- custom modelbinder for datetime
I have no idea how to force it and I need to input the date as dd/MM/yyyy not the default.
MORE INFO:
my viewmodel is like this
[DisplayName("date of birth")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? Birth { get; set; }
in view I use @Html.DisplayFor(m=>m.Birth)
but this works as expected (I see the formatting)
and to input the date I use @Html.EditorFor(m=>m.Birth)
but if I try and input something like 13/12/2000 is fails with the error that it is not a valid date (12/13/2000 and 2000/12/13 are working as expected but I need dd/MM/yyyy).
The custom modelbinder is called in application_start() b/c I don't know where else.
Using <globalization/>
I have tried with culture="ro-RO", uiCulture="ro"
and other cultures that would give me dd/MM/yyyy.
I have also tried to set it on a per thread basis in application_start() (there are a lot of examples here, on how to do this)
For all that will read this question:
It seems that Darin Dimitrov's answer will work as long as I don't have client validation.
Another approach is to use custom validation including client side validation.
I'm glad I found this out before recreating the entire application.
Best Answer
Ahhhh, now it is clear. You seem to have problems binding back the value. Not with displaying it on the view. Indeed, that's the fault of the default model binder. You could write and use a custom one that will take into consideration the
[DisplayFormat]
attribute on your model. I have illustrated such a custom model binder here: https://stackoverflow.com/a/7836093/29407Apparently some problems still persist. Here's my full setup working perfectly fine on both ASP.NET MVC 3 & 4 RC.
Model:
Controller:
View:
Registration of the custom model binder in
Application_Start
:And the custom model binder itself:
Now, no matter what culture you have setup in your web.config (
<globalization>
element) or the current thread culture, the custom model binder will use theDisplayFormat
attribute's date format when parsing nullable dates.