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

本文关键字:格式 日期 dd mm yyyy MVC3 NET 控制器 ASP | 更新日期: 2023-09-27 18:17:29

基本上,我的日期选择器使用英国格式的dd/mm/yyyy。但是当我提交表格时,ASP.net 显然使用的是美国格式。(如果少于 12 天,则只接受天数,即认为是月份。

 public ActionResult TimeTable(DateTime ViewDate)

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

奇怪的是,其他插入方法似乎可以识别正确的格式。

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

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

阅读此内容。它很好地解释了正在发生的事情以及为什么它如此工作。

我知道使用该站点的每个人都在英国,因此我可以安全地覆盖默认的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;
        }
    }
}

您需要为日期时间使用自定义模型绑定器。我和你有同样的问题。

您是否尝试过将当前区域性设置为 en-GB?

protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
     base.Initialize(requestContext);
     CultureInfo cultureInfo = CultureInfo.GetCultureInfo("en-GB");
     Thread.CurrentThread.CurrentCulture = cultureInfo;
     Thread.CurrentThread.CurrentUICulture = cultureInfo;                    
 }

你可以这样做:

  • 全局(在 global.asax 中,在 Application_Start(( 下(:

    ModelBinders.Binders.Add(typeof(DateTime), new DateTimeModelBinder()); 
    
  • 对于方法:

        public ActionResult TimeTable([Binder(typeof(DateTimeModelBinder)]DateTime ViewDate)
    
  • 对于自定义模型类 - 啊不,没有可能性,因为您使用结构 DateTime ;-(

啊,对不起,我无法在亚当斯的帖子中添加评论 - 这是基于他的代码。

基本上,我的日期选择器使用英国格式的 dd/mm/yyyy

初学者错误。它应该使用浏览器设置为的任何格式。问题不在于格式,而在于客户端和服务器之间的不同格式。服务器应发出代码,根据协商的区域设置设置日期的格式,然后服务器也使用该区域设置来解析日期。

但是当我提交表格时,ASP.NET 显然使用的是美国格式。

不。这是说,当我服用香料时,它总是盐,然后你总是服用盐。您的服务器接受当前协商的区域性,除非您修改设置,否则该区域性在客户端和服务器之间进行协商。检查线程当前区域性何时应执行分析,以查看其设置目的。

来自我的 BindigTools for binding DateTime?(可为空(,基于某些书籍示例 - Pro MVC3

    public static DateTime? GetValueNDateTime(ModelBindingContext context, string searchPrefix, string key, string format)
    {
        ValueProviderResult vpr = context.ValueProvider.GetValue(searchPrefix + key);
        DateTime outVal;
        if (DateTime.TryParseExact(vpr.AttemptedValue, format, null, System.Globalization.DateTimeStyles.None, out outVal))
        {
            return outVal;
        }
        else
        {
            return null;
        }
    }

它使用精确解析,因此解析日期应该没有任何问题。