开发者

Custom date format problem in MVC application

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>
开发者_如何学Python

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜