首页 新闻 赞助 找找看

请教一下,Asp.net mvc 5(C#)默认的model验证错误消息如何实现多国语言(读取资源文件)

0
悬赏园豆:5 [待解决问题]

我用资源文件实现了网站多语言,大部分都可以了,可是验证错误消息The field 生日 must be a date(即The field {0} must be a date.).它貌似是mvc里面model默认验证消息。请教一下如何改为读取资源文件中的值。

时光刺客的主页 时光刺客 | 初学一级 | 园豆:60
提问于:2014-10-12 20:49
< >
分享
所有回答(2)
0

那是验证视图出错了吧。你需要调用那个属性的重载实现显示的区域语言

Cherbim | 园豆:323 (菜鸟二级) | 2014-10-12 22:16
0

可以自己自定义对应的AttributeAdapter解决这个问题。

例如自定义RequiredAttributeAdapter

/// <summary>
        /// Required
        /// </summary>
        public class LocationRequiredAdapter : RequiredAttributeAdapter
        {
            public LocationRequiredAdapter(ModelMetadata metadata, ControllerContext context, RequiredAttribute attribute)
                : base(metadata, context, attribute)
            {

            }

            public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
            {
                return new[]
                    {
                        new ModelClientValidationRequiredRule(string.Format("{0}",
                                                                            this.ErrorMessage.Trans()
                                                                  ))
                    };
            }
        }

this.ErrorMessage.Trans()”在我的项目里面就是把错误信息翻译成当前语言。

webaspx | 园豆:1973 (小虾三级) | 2014-10-13 13:24

这方法也写太多代码了吧!我最后网上找到的方法只需要2行代码(不计写资源文件的)

protected void Application_Start()
        {
            //通过资源文件本地化默认的错误提示
            ClientDataTypeModelValidatorProvider.ResourceClassKey = "资源文件名称";
            DefaultModelBinder.ResourceClassKey = "资源文件名称";
        }

.resx资源文件
名称:FieldMustBeDate  值:你自定义显示的内容
名称:FieldMustBeNumeric 值:你自定义显示的内容
名称:PropertyValueInvalid 值:你自定义显示的内容
名称:PropertyValueRequired 值:你自定义显示的内容

参考这个的http://weblogs.asp.net/imranbaloch/localizing-default-error-messages-in-asp-net-mvc-and-web-form

支持(0) 反对(0) 时光刺客 | 园豆:60 (初学一级) | 2014-10-14 19:20

@时光刺客: 嗯,确实你那方法挺好的。我们用那方法是因为我们的翻译不是使用资源文件。

支持(0) 反对(0) webaspx | 园豆:1973 (小虾三级) | 2014-10-15 08:37
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册