Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question

1 Answer 1

up vote 0 down vote accepted

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.

share|improve this answer
    
This solution works but the example in the link is deprecated because IModelBinder interface have now another signature. –  mast3r Sep 9 '11 at 12:38
    
Another possible solution consists to change in Region and Language the formats of date and time. –  mast3r Sep 9 '11 at 12:50

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.