MVC应用程序中自定义日期格式问题
我有以下模型和视图,我非常希望接受格式为“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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试在 web.config 中设置
uiCulture
(如果将其保留为auto
,则将使用客户端浏览器区域性):当默认模型绑定器解析请求值时,这将强制使用
en-US
区域性格式(根据需要进行调整)到所需的文化)。另外,将
Date
属性输入到System.Object
也不是一个很好的设计。Try setting the
uiCulture
in web.config (If you leave it toauto
the client browser culture will be used):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 toSystem.Object
is not a very good design.