2011-04-12 104 views
1

我传递的日期到我的服务器不变文化,格式如下MVC 1参数绑定

'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

binderDictionary.Add(typeof(DateTime), new DateTimeModelBinder()); 

这不起作用增加IModelBinder到binderDictionary的实现,而且也不

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

这似乎是一些人会想要一直做的。我看不出为什么要在服务器上的当前文化中解析日期等。客户端将不得不找出服务器的文化,只是为了格式化日期服务器将能够解析.....

任何帮助表示赞赏!

回答

2

我在这里已经解决了这个问题,我已经错过了,在对象,日期时间是可空

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

因此我粘结剂WASN不被接受。

如果有人有兴趣,这是我做过什么....

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

希望这会派上用场别人.....

0

是否可以通过ISO 8601格式将日期传递给服务器?我认为服务器会正​​确解析,无论其区域设置如何。

1

是您的问题,您的自定义模型联编程序无法解析某些输入日期或您的自定义模型联编程序永远不会被调用?如果是前者,那么试图使用用户浏览器的文化可能会有所帮助。

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()); 
+0

的问题是,我的自定义模型绑定器永远不会被调用 – Gaz 2011-04-13 08:00:23