views:

62

answers:

2

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.

A: 

Why is your type Object and not DateTime?

Brent Miller
The property that is of type `object` is only a "buddy class" property, to pop the annotation attributes onto. This is quite standard practice with "buddy class" metadata.
ProfK
+3  A: 

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.

Darin Dimitrov
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.
ProfK
In this case you would need to write a custom model binder and manually parse the request string into a DateTime.
Darin Dimitrov
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.
ProfK