将日期参数传递给对MVC操作的ajax调用的安全方法 [英] Safe way to pass a date param to an ajax call to a MVC action
问题描述
我有一个MVC操作,它的一个参数是 DateTime
,如果我传递17/07/2012,它会抛出一个异常,说该参数为null但不能有空值,但如果我通过 01/07/2012
,它将被解析为 2012年1月7日
。
I have a MVC action that takes one of its parameters a DateTime
and if I pass "17/07/2012" it throws an exception saying that the param is null but cannot have a null value but if I pass 01/07/2012
it is parsed as Jan 07 2012
.
我将日期传递给 DD / MM / YYYY
格式的ajax调用,我应该依赖 MM / DD / YYYY
格式,尽管在 web.config中配置了文化
?
I'm passing the dates to the ajax call in DD/MM/YYYY
format, should I rely on MM/DD/YYYY
format despite the configured culture in web.config
?
这是一个简单的方法,只有一个日期参数。
This is a simple method and there is just this one date parameter.
推荐答案
你有三个安全的选择在Asp.NET-MVC中发送日期参数:
You got three safe options to send date parameter in Asp.NET-MVC:
- 将其发送为
YYYY / MM / DD
这是国际日期的ISO标准。 -
使用
POST
请求而不是GET
request。
- Send it as
YYYY/MM/DD
it's the ISO standard for international dates. Use
POST
request instead ofGET
request.
如果要更改默认 Model Binder
绑定日期:
If you want to change the way the default Model Binder
binds dates:
你可以使用IModelBinder更改默认模型绑定器以使用用户文化
you can change the default model binder to use the user culture using IModelBinder
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中写道:
And in the Global.Asax write:
ModelBinders.Binders.Add(typeof(DateTime), new DateTimeBinder());
ModelBinders.Binders.Add(typeof(DateTime?), new DateTimeBinder());
在这个优秀的博客描述了Mvc框架团队为所有用户实施默认文化的原因。
Read more at this excellent blog that describe why Mvc framework team implemented a default Culture to all users.
这篇关于将日期参数传递给对MVC操作的ajax调用的安全方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!