When i try to create or save a date in the model the validation trows invalid date format instead of respect my format specified in DataFormatString (dd/MM/yyyy). I saw that the framework try to save the date only in MM/dd/yyyy format. I want to input/output it in dd/MM/yyyy.
I have the following model:
public class MyModel {
public int MyModelID { get; set; }
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime BornDate { get; set; }
}
I have the edit template to display data edited:
@model DateTime?
@Html.TextBox("", Model.HasValue ? Model.Value.ToString("dd/MM/yyyy") : DateTime.Today.ToString("dd/MM/yyyy"), new { @class = "date" })
I have a jquery date picker registered with the following code:
$(document).ready(function () {
$('.date').datepicker({
changeMonth:开发者_如何学运维 true,
changeYear: true,
dateFormat: "dd/mm/yy"
});
});
I have the following view with:
<div class="editor-field">
@Html.EditorFor(model => model.DataNascimento)
@Html.ValidationMessageFor(model => model.DataNascimento)
</div>
I have checked ContosoUniversity tutorial and it happens to.
Thanks for help.
One of the better options to solve this, is writing you own ModelBinder to handle localization, read more about that here
The attribute DisplayFormat
is specifies only how BornDate field is displayed (and formatted upon displaying), when using @Html.EditorFor
for instance.
精彩评论