3

I have the following model and view, and I would very much like to accept date values in the format 'dd/MM/yyyy'. However, despite using the DisplayFormat annotation, I still get a validation error using my chosen format.

[MetadataType(typeof(MilestoneMetadata))]
public partial class Milestone {    
    public class MilestoneMetadata {
        [Required][DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
        public object Date { get; set; }
    }
}

and the view:

<div class="editor-field">
    <%: Html.EditorFor(model => model.Date) %> 
    <%: Html.ValidationMessageFor(model => model.Date) %>
</div>

Namespaces etc. are correct for the annotations and main classes to be in the same namespace. This is not my first encounter with this issue, but I see no results from annotations that are supposed to affect mappings between form values and the model. A template for dates doesn't help me because I can't find a way to set how dates are parsed when posting a create or update.

NOTE: I do not wish to use a different UI culture to achieve this.

1 Answer 1

5

Try setting the uiCulture in web.config (If you leave it to auto the client browser culture will be used):

<globalization uiCulture="en-US" 
               requestEncoding="utf-8" 
               responseEncoding="utf-8" />

This will force en-US culture format when the default model binder parses request values (adapt as necessary to the needed culture).

Also having a Date property typed to System.Object is not a very good design.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Darin, I've found if I set culture to 'en-GB', I get the correct format handling. If I set it to 'en-ZA', I have to use the format 'yyyy/MM/dd'. My real goal is to not change the culture, but still change the date format. The property that is of type System.Object is never used. The real date property is declared as System.DateTime. The 'object' property is only used for it's attributes.
In this case you would need to write a custom model binder and manually parse the request string into a DateTime.
Yeah, thanks. I have already done a model binder for all DateTime values, but this seems like an extraordinary length to go to for a task like this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.