我有一个 MVC 操作,它的参数之一是 DateTime
,如果我传递“17/07/2012”,它会抛出一个异常,指出参数为 null 但不能有 null 值但如果我传递 01/07/2012
,它会被解析为 Jan 07 2012
。
我正在以 DD/MM/YYYY
格式将日期传递给 ajax 调用,我是否应该依赖 MM/DD/YYYY
格式,尽管在web.config
?
这是一个简单的方法,只有一个日期参数。
最佳答案
在 Asp.NET-MVC 中,您有三个安全选项来发送日期参数:
- 将其作为
YYYY/MM/DD
发送,这是国际日期的 ISO 标准。 使用
POST
请求代替GET
请求。如果您想更改默认
Model Binder
绑定(bind)日期的方式:
您可以使用 IModelBinder 更改默认模型绑定(bind)器以使用用户区域性
public class DateTimeBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
var date = value.ConvertTo(typeof(DateTime), CultureInfo.CurrentCulture);
return date;
}
}
并在 Global.Asax 中写入:
ModelBinders.Binders.Add(typeof(DateTime), new DateTimeBinder());
ModelBinders.Binders.Add(typeof(DateTime?), new DateTimeBinder());
阅读更多信息 this excellent blog描述了为什么 Mvc 框架团队为所有用户实现了默认文化。
关于c# - 将日期参数传递给对 MVC 操作的 ajax 调用的安全方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10519748/