如何指定模型绑定日期格式? [英] How to specify date format for model binding?

查看:118
本文介绍了如何指定模型绑定日期格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望这个问题很容易,但我一个多小时搜索周围,我只是没有找到答案。所以我有一个asp.net MVC 2应用的形式之一包含一个jQuery日期选择日期文本框。我在日期选择器的日期格式设置为 DD.MM.YYYY 。我的问题是在模型绑定这个日期作为PTED MM.DD.YYYY 间$ P $,所以由当时的模型达到我的行动方法的datetime属性该模型是不正确的(日,月反转,如果它是不可能扭转它的客户端验证并不让我保存该项目)。我并不想改变文化,但我想以某种方式指定模型绑定如何跨preT的日期。是否有可能以某种方式?

I hope the question is easy, but I am searching around for more than an hour and I just do not find the answer. So I have a asp.net mvc 2 application and one of the forms contains a date textbox with a jquery datepicker. I have set in the datepicker the date format to be dd.mm.yyyy. My problem is that on the model binding this date is interpreted as mm.dd.yyyy, so by the time the model reaches my action method the DateTime attribute of the model is not correct (day and month is reversed, if it is not possible to reverse it client side validation does not let me save the item). I do not want to change culture, but I would like to specify somehow to the model binder how to interpret the date. Is it possible somehow?

非常感谢

推荐答案

这个博客帖子解释了如何指定一个特定的日期格式由MVC模型粘合剂使用。

This blog post explains how you can specify a particular date format to be used by the MVC model binder.

您需要创建一个自定义模型绑定实现,知道的日期格式,然后在您的Global.asax.cs相关联,与DateTime类型:

You will need to create a custom model binder implementation that is aware of the date format, then associate that with the DateTime type in your Global.asax.cs:

protected void Application_Start()
{
    //...
    var binder = new DateTimeModelBinder(GetCustomDateFormat());
    ModelBinders.Binders.Add(typeof(DateTime), binder);
}

这篇关于如何指定模型绑定日期格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆