我将MVC3解决方案升级为MVC4。迁移后,验证程序已损坏。
如果我选择德语作为语言,我的输入日期是“20.03.2013”。我在MVC4中得到验证错误,但在MVC3中没有。如果我将格式从“20.03.2013”替换为“20/03/2013”,它适用于MVC4,但不适用于MVC3 ;-)
我将当前线程的UI文化设置为德语。 ResX值的输出使用正确的语言, 所以我知道文化应该没有错误。,仅适用于网站本身。错误消息是英文的,但该网站是德语。
我认为这意味着验证器使用了错误的UI文化。
这是我使用的代码。
[必需(ErrorMessageResourceName =“Error_DepartureDate”,ErrorMessageResourceType = typeof(Resx.Query))] 公共日期时间? DepartureDate {get;组; }
我假设默认模型绑定器有问题,因为渲染的html看起来很好:
data-lang =“de”data-mindate =“3”data-val =“true”data-val-required =“Bitte geben SiedasgewünschteReisedatumdes Hinflugs ein。” id =“DepartureDate”name =“DepartureDate”tabindex =“3”type =“text”value =“”
我将Jscript升级到使用Visual Studio 2012(已安装SP1)模板创建新Mvc应用程序时发布的源代码。这没有任何影响。
我有一个CultureModelBinder,它从Session中读取当前的文化,并使用一个小帮助函数设置文化。
public static void UpdateThreadCulture(CultureInfo culture) { Thread.CurrentThread.CurrentUICulture = culture; }
culture文件模型binder是默认的binder。
ModelBinders.Binders.DefaultBinder = new CultureModelBinder(); ModelBinders.Binders.Add(typeof(DateTime?),new DateTimeModelBinder()); //还有很多很多
也许mvc4的执行顺序发生了变化,导致问题?
更新:该项目使用.NET Framework 4.5作为目标。
更新2:
我有一个组合框,用户可以选择16种不同的语言,每种语言都有自己特定的格式。
例如。 DE-de - > DD.MM.YYYY; en-en - > DD / MM / YYYY; en-us - > MM / DD / YYYY
我刚刚提到了关于设置当前文化的暗示,这里证明它应该是正确的。当验证器失败时,不会触发此代码,看起来它发生在客户端。
public class DateTimeModelBinder:IModelBinder { private LogService _log = new LogService(); public object BindModel(ControllerContext controllerContext,ModelBindingContext bindingContext) { object result = null; ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); if(valueResult!= null) { 尝试 { var stateHandler = new StateHandler(controllerContext.HttpContext.Session); result = valueResult.ConvertTo(typeof(DateTime?),stateHandler.Culture); } 抓住 { 尝试 { result = valueResult.ConvertTo(typeof(DateTime?),CultureInfo.InvariantCulture); } catch(Exception ex) { _log.Error(“DateTimeModelBinder parse exception”,ex); _log.KeyValue(“AttemptedValue”,valueResult.AttemptedValue); } } } 返回结果; } }
为了完整我的文化模型粘合剂:
public class CultureModelBinder:DefaultModelBinder { 公共覆盖对象BindModel(ControllerContext controllerContext,ModelBindingContext bindingContext) { StateHandler stateHandler = new StateHandler(controllerContext.HttpContext.Session); Helper.UpdateThreadCulture(stateHandler.Culture); return base.BindModel(controllerContext,bindingContext); } }
更新: 阅读以下文章: http://weblogs.asp.net/scottgu/archive/2010/06/10/jquery-globalization-plugin-from-microsoft.aspx
尝试以下方法:
按以下顺序加载脚本:
/Scripts/jquery-1.8.3.min.js /Scripts/globalize.js /Scripts/cultures/globalize.cultures.js //以及更多其他脚本......
加了电话。输出正确“DE”。
var currentLanguage = $(“#DepartureDate”)。attr(“data-lang”); 警报(currentLanguage); $ .preferCulture(currentLanguage);
对验证者没有影响......