我在Invariant Culture中将日期传递给我的服务器,格式如下
'mm/dd/yy'
MVC中的参数绑定无法解析此日期并为参数返回null。这可能是因为IIS在使用英语文化的机器上运行('dd / mm / yy'工作正常)。
我想覆盖我服务器上所有日期的解析,以便像这样使用Invariant Culture ...
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'
我已经尝试将IModelBinder的实现添加到global.asax中的binderDictionary
binderDictionary.Add(typeof(DateTime), new DateTimeModelBinder());
这不起作用,也不起作用
ModelBinders.Binders.Add(typeof(DateTime), new DataTimeModelBinder());
这似乎有些人希望一直这么做。我不明白为什么你要解析服务器上当前文化中的日期等。客户端必须找出服务器的文化,以便格式化服务器能够解析的日期.....
任何帮助表示赞赏!
答案 0 :(得分:2)
我已经在这里解决了问题,我错过的是在对象中,日期时间是可以为空的
public class MyObj
{
public DateTime? Date { get; set; }
}
因此我的活页夹没有被拿起。
如果有人有兴趣,这就是我做的......
在global.asax中添加了以下内容
binderDictionary.add(typeof(DateTime?), new InvariantBinder<DateTime>());
像这样创建了一个不变的活页夹
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);
}
}
希望这对别人来说很方便.....
答案 1 :(得分: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());
答案 2 :(得分:0)
是否可以以ISO 8601格式将日期传递给服务器?我认为服务器无论其自身的区域设置如何都会正确解析。