MVC 1参数绑定

本文关键字:绑定 参数 MVC | 更新日期: 2023-09-27 17:50:02

我将一个日期以不变区域性传递给服务器,格式如下

'mm/dd/yy'

MVC中的参数绑定无法解析此日期并为参数返回null。这可能是因为IIS运行在使用英语文化的机器上('dd/mm/yy'可以正常工作)。

我想覆盖我的服务器上的所有日期的解析使用不变文化,像这样…

Convert.ChangeType('12/31/11', typeof(DateTime), CultureInfo.InvariantCulture);

即使日期是另一个对象的一部分…

public class MyObj
{
    public DateTime Date { get; set; }
}

控制器方法是这样的....

public ActionResult DoSomethingImportant(MyObj obj)
{
     // use the really important date here
     DoSomethingWithTheDate(obj.Date);
} 

日期作为Json数据发送,如....

myobj.Date = '12/31/11'

我尝试在global.asax

中将IModelBinder的实现添加到binder字典中。
binderDictionary.Add(typeof(DateTime), new DateTimeModelBinder());

不行,

也不行
ModelBinders.Binders.Add(typeof(DateTime), new DataTimeModelBinder());

这似乎是一些人一直想要做的。我不明白你为什么要在服务器上的当前文化中解析日期等。客户端必须找出服务器的区域性,以便格式化服务器能够解析的日期.....

感谢任何帮助!

MVC 1参数绑定

我已经解决了这里的问题,我错过的是在对象中,datetime是可空的

public class MyObj
{
    public DateTime? Date { get; set; }
}

因此我的活页夹没有被拿起来。

如果有人感兴趣,这就是我所做的....

  1. 在全局。Asax添加了以下内容

    binderDictionary.add(typeof(DateTime?), new InvariantBinder<DateTime>());
    
  2. 创建如下的不变绑定

    public class InvariantBinder<T> : IModelBinder
    {
        public object BindModel(ControllerContext context, ModelBindingContext binding)
        {
            string name = binding.ModelName;
            IDictionary<string, ValueProviderResult> values = binding.ValueProvider;
            if (!values.ContainsKey(name) || string.IsNullOrEmpty(values[names].AttemptedValue)
                return null;
            return (T)Convert.ChangeType(values[name].AttemptedValue, typeof(T), CultureInfo.Invariant);
        }
    }
    

希望这对其他人有用.....

您的问题是您的自定义模型绑定器无法解析一些输入日期或您的自定义模型绑定器从未被调用?如果是前者,那么尝试使用用户浏览器的文化可能会有所帮助。

public class UserCultureDateTimeModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        object value = controllerContext.HttpContext.Request[bindingContext.ModelName];
        if (value == null)
            return null;
        // Request.UserLanguages could have multiple values or even no value.
        string culture = controllerContext.HttpContext.Request.UserLanguages.FirstOrDefault();
        return Convert.ChangeType(value, typeof(DateTime), CultureInfo.GetCultureInfo(culture));
    }
}

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

是否可以将日期以ISO 8601格式传递给服务器?我认为服务器会正确解析,不管它自己的区域设置。