2
I can’t get the date formatting right in my forms. I 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; }
Upshot:
Accepts everything, does not validate anything. And brings the full date, including in the views where I used @Html.DisplayFor(modelItem => item.Data)
. I wanted the abbreviated en-br.
Case 2: Using Datatype Annotation
[DataType(DataType.Date)]
public DateTime Data { get; set; }
Upshot:
Improved, now already formats the date (including in the views I used DisplayFor()
), but in a data view it does not show and yes dd/mm/aaaa
. I fill in 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 I used DisplayFor()
and when I open a view with EditorFor()
the field displays the summarized date, formatted and with the datapicker. But when you change the date the validation does not accept in any way the informed date.
I broke my head two days looking for a solution, I’m using Nuget Globalization with Culture configured on Web.config
and would like to do this in the most academic way possible (that is, directly in the model or at most passing some attribute to the component in the view, avoiding at most changing the existing standard Javascript).
You added jQuery-Validate-Globalize and Globalize to your solution?
– Leonel Sanches da Silva
I had not added jQuery-Validate-Globalize. I added and corrected the
EditorFor()
. But in the views I useDisplayFor()
the date appears2015-07-14
.– Marnei
Yes, it is true. I would like to complement this as an answer?
– Leonel Sanches da Silva
Yes, please. And thank you for your help!
– Marnei