MVC应用程序中自定义日期格式问题

发布于 2024-09-28 00:40:45 字数 781 浏览 0 评论 0原文

我有以下模型和视图,我非常希望接受格式为“dd/MM/yyyy”的日期值。但是,尽管使用了 DisplayFormat 注释,但使用我选择的格式时我仍然收到验证错误。

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

视图:

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

命名空间等对于注释和主类位于同一命名空间中是正确的。这不是我第一次遇到这个问题,但我没有看到应该影响表单值和模型之间映射的注释的结果。日期模板对我没有帮助,因为我找不到一种方法来设置在发布创建或更新时如何解析日期。

注意: 我不希望使用不同的 UI 文化来实现此目的。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

淡水深流 2024-10-05 00:40:45

尝试在 web.config 中设置 uiCulture (如果将其保留为 auto ,则将使用客户端浏览器区域性):

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

当默认模型绑定器解析请求值时,这将强制使用 en-US 区域性格式(根据需要进行调整)到所需的文化)。

另外,将 Date 属性输入到 System.Object 也不是一个很好的设计。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文