首页 文章

在HTTP GET中绑定en-GB日期

提问于
浏览
8

我和Dates度过了一段噩梦 . 我们的总部设在英国,因此我们的日期格式为dd / MM / yyyy . 这是用户在需要特定日期时将在表单中键入的内容 . 我有一个表格只接受这样的 property . 它显然是一个DateTime类型 . 我想在GET中将此表单发送到控制器,因此用户有一个很好的URL,他们可以保存传递,等等 . 视图还需要将JQuery UI datepicker绑定到此元素 . 我还需要表单元素具有一定的id和类,所以我真的需要将其呈现给表单:

@Html.TextBoxFor(model => model.ReturnDate, new { Class = "date", id = "ReturnDate" })

我在web.config中指定了一个英国文化变体:

<globalization uiCulture="en" culture="en-GB"/>

但是,正如这里所解释的那样(http://weblogs.asp.net/melvynharbour/archive/2008/11/21/mvc-modelbinder-and-localization.aspx),当获取控制器启动时,MVC忽略了文化变体并默认为美国(显然没有人存在于美国以外,所以这对微软来说没问题,咆哮)附件不帮助,因为这意味着我必须为 every date in every model! 设置它

这意味着如果用户输入01/05/2012,我最终会遇到05/01/2012,这是错误的!

我已经看过这个问题的各种解决方案,但没有一个真正符合我的需要 . 我需要一种方法,以便 All dates sent via a GET are in UK format . 我们完全位于英国,因此不会输入任何英国格式 .

我真的不想创建和编辑,除非它是一种我可以在没有附加到此编辑器的View / Viewmodel的情况下执行此操作的方法,因为在我们有日期选择器的任何地方使用它都会非常笨拙 .

所有的帮助将非常感谢!

2 回答

  • 2

    得到一个解决方案,感谢@Jon的指针:

    public class GBDateModelBinder : IModelBinder
    {
    
        #region IModelBinder Members
    
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            string dateString = controllerContext.HttpContext.Request.QueryString[bindingContext.ModelName];
            if (string.IsNullOrEmpty(dateString))
                     dateString = controllerContext.HttpContext.Request.Form[bindingContext.ModelName];
            DateTime dt = new DateTime();
            bool success = DateTime.TryParse(dateString, CultureInfo.GetCultureInfo("en-GB"), DateTimeStyles.None, out dt);
            if (success)
            {
                return dt;
            }
            else
                {
                return null;
            }
        }
    
        #endregion
    }
    

    然后在global.asax中注册:

    ModelBinders.Binders.Add(typeof(DateTime), new GBDateModelBinder());
    

    UPDATE

    修改此项以在POST时允许相同的问题!

  • 10

    除了利亚姆的回答:

    对于那些仍然遇到此问题(!)并且正在尝试绑定到Nullable DateTime的人,请确保在global.asax中注册了正确的类型:

    ModelBinders.Binders.Add(typeof(DateTime), new GBDateModelBinder());
    ModelBinders.Binders.Add(typeof(DateTime?), new GBDateModelBinder());
    

    让我难过了15分钟!

相关问题