在HTTP GET中绑定en-GB日期

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

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

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

  

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

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

我已经看过这个问题的各种解决方案,但没有一个真正符合我的需要。 我需要一种方法,以便通过GET发送的所有日期都是英国格式 。 我们完全位于英国,因此不会输入任何英国格式。

我真的不想创建和编辑,除非他们没有连接到这个编辑器的View / Viewmodel就可以做到这一点,因为在我们有一个日期选择器的任何地方使用它都会非常笨拙。

所有帮助将非常感谢!

得到一个解决方案,感谢@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时允许相同的问题!

除了利亚姆的回答:

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

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

让我难过了15分钟!