I can not set the formatting of dates on my forms. I've tried several cases, all using the same view:
@Html.EditorFor(model => model.Data, new { htmlAttributes = new { @class = "form-control" } })
Case 1: Clean and raw
public DateTime Data { get; set; }
Result:
It accepts everything, it does not validate at all. And it brings the complete date, even in the views where I used @Html.DisplayFor(modelItem => item.Data)
. I wanted the abbreviated pt-BR.
Case 2: Using Annotation DataType
[DataType(DataType.Date)]
public DateTime Data { get; set; }
Result:
Improved, now format the date (including in the views I used DisplayFor()
), but in a view with data it does not show them and dd/mm/aaaa
. I fill in with any date by typing or selecting in the datapicker and it accepts and overwrites the saved date.
Case 3: Using DataType and DisplayFormat
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
[Required(ErrorMessage = "Informe a data deste lançamento.")]
public DateTime Data { get; set; }
Result:
Visually perfect. In the views that I used DisplayFor()
was as it wanted and when I open a view with EditorFor()
the field displays the date summarized, formatted and with the datapicker. But when you change the date the validation does not accept the reported date in any way.
I broke my head for two days looking for a solution, I'm using NuGet's Globalization with culture set to Web.config
and I'd like to do it in the most academic way possible (ie directly in the model or at most passing some attribute to the component in the view, avoiding as much as possible to change the existing default Javascript).