ASP.NET MVC3:强制控制器使用日期格式dd/mm/yyyy

Doo*_*ght 13 c# asp.net asp.net-mvc-3

基本上,我的datepicker使用英国格式dd/mm/yyyy.但是当我提交表单时,ASP.net显然使用美国格式.(只接受少于12天,即认为是月份.)

 public ActionResult TimeTable(DateTime ViewDate)
Run Code Online (Sandbox Code Playgroud)

有没有办法强迫它识别某种方式?

奇怪的是,其他插入方法似乎都能识别正确的格式.

"参数字典包含参数提供一个空条目ViewDate非空类型的System.DateTime用于方法System.Web.Mvc.ActionResult Index(System.DateTime)Mysite.Controllers.RoomBookingsController一个可选的参数必须是引用类型,可空类型,或声明为可选参数".

Ada*_*gan 16

有读这个.它可以很好地解释发生了什么以及它为什么会起作用.

我知道每个使用该网站的人都在英国,所以我可以安全地覆盖默认的DateTime模型绑定器:

public class DateTimeModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var date = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).AttemptedValue;

        if (String.IsNullOrEmpty(date))
            return null;

        bindingContext.ModelState.SetModelValue(bindingContext.ModelName, bindingContext.ValueProvider.GetValue(bindingContext.ModelName));
        try
        {
            return DateTime.Parse(date);
        }
        catch (Exception)
        {
            bindingContext.ModelState.AddModelError(bindingContext.ModelName, String.Format("\"{0}\" is invalid.", bindingContext.ModelName));
            return null;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我将上面的代码放在Binders目录中的自己的文件中.然后,你需要在`Application_Start()`中注册一个类似于`ModelBinders.Binders.Add(typeof(DateTime),new DateTimeModelBinder())的绑定器. (2认同)