在对某个DateTime模型属性使用“远程”验证属性时,我遇到了一些不必要的行为。
服务器端,我的应用程序文化定义如下:
protected void Application_PreRequestHandlerExecute()
{
if (!(Context.Handler is IRequiresSessionState)){ return; }
Thread.CurrentThread.CurrentCulture = new CultureInfo("nl-BE");
Thread.CurrentThread.CurrentUICulture = new CultureInfo("nl-BE");
}客户端,我的应用程序文化定义如下:
Globalize.culture("nl-BE");案例1:
IsDateValid方法时,在UI中输入为05/10/2013的日期(2013年10月5日)被错误地解释为10/05/2013 (2013年5月10日)案例2:
IsDateValid方法时,在UI中输入的日期为05/10/2013 (2013年10月5日),正确地将解释为05/10/2013 (2013年10月5日)我是否缺少一些配置,使“标准”得到远程验证工作,如所需?
发布于 2013-11-29 11:49:10
当为GET绑定数据时,使用InvariantCulture (即"en-US"),而对于POST Thread.CurrentThread.CurrentCulture则使用。背后的原因是GET urls可能被用户共享,因此应该是不变的。而POST从来都不是共享的,使用服务器的区域性在那里绑定是安全的。
如果您确信您的应用程序不需要在来自不同国家的人之间共享urls,那么您可以安全地创建自己的ModelBinder,它将强制使用服务器区域设置,甚至对于GET请求也是如此。
下面是Global.asax.cs中的示例:
protected void Application_Start()
{
/*some code*/
ModelBinders.Binders.Add(typeof(DateTime), new DateTimeModelBinder());
ModelBinders.Binders.Add(typeof(DateTime?), new DateTimeModelBinder());
}
/// <summary>
/// Allows to pass date using get using current server's culture instead of invariant culture.
/// </summary>
public class DateTimeModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
var date = valueProviderResult.AttemptedValue;
if (String.IsNullOrEmpty(date))
{
return null;
}
bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);
try
{
// Parse DateTimeusing current culture.
return DateTime.Parse(date);
}
catch (Exception)
{
bindingContext.ModelState.AddModelError(bindingContext.ModelName, String.Format("\"{0}\" is invalid.", bindingContext.ModelName));
return null;
}
}
}https://stackoverflow.com/questions/19292702
复制相似问题