ASP.NET MVC3:力控制器使用日期格式DD / MM / YYYY [英] ASP.NET MVC3: Force controller to use date format dd/mm/yyyy

查看:100
本文介绍了ASP.NET MVC3:力控制器使用日期格式DD / MM / YYYY的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我的日期选择器使用 DD / MM / YYYY 英国格式。但是,当我提交表单,ASP.net显然是使用美国格式。
(只会如果少于12天接受的,即认为这是一个月)。

Basically, my datepicker uses UK format of dd/mm/yyyy. But when I submit the form, ASP.net is clearly using US format. (will only accept days if less than 12, i.e. thinks it is the month.)

 public ActionResult TimeTable(DateTime ViewDate)

有没有办法迫使它承认某种方式?

Is there a way to force it to recognise a certain way?

虽然奇怪,插入其他方法似乎认识到正确的格式。

Strangely though, other methods of insert seem to recognise the correct format.

参数词典共包含非可空类型的System.DateTime 的参数 ViewDate 的方法的无效项 System.Web.Mvc.ActionResult指数(的System.DateTime) Mysite.Controllers.RoomBookingsController 一个可选的参数必须引用类型,可空类型,或声明为可选参数。

"The parameters dictionary contains a null entry for parameter ViewDate of non-nullable type System.DateTime for method System.Web.Mvc.ActionResult Index(System.DateTime) in Mysite.Controllers.RoomBookingsController. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter."

推荐答案

有一个读<一个href=\"http://weblogs.asp.net/melvynharbour/archive/2008/11/21/mvc-modelbinder-and-localization.aspx\">this.它提供了发生的事情的一个很好的解释,为什么它的工作,它的作用。

Have a read of this. It gives a good explanation of what's happening and why it works as it does.

我在哪里,我知道每个人都使用该网站是在英国,所以我可以放心地覆盖默认的情况的DateTime 模型绑定:

I'm in the situation where I know everyone using the site is in the UK so I can safely override the default DateTime model binder:

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;
        }
    }
}

这篇关于ASP.NET MVC3:力控制器使用日期格式DD / MM / YYYY的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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