如何修改默认的ModelState错误提示:字段{0}必须是一个数字

      当使用ViewModel并且某个属性为int或decimal等值类型时,我们如果使用Html.TextBoxFor或Html.TextBox方法,则输入了非数字字符,后台会自动校验,并提示:字段{0}必须是一个数字。

      有时候我们需要自定义这个提示,具体可自定义一个ModelBinder类,继承自DefaultModelBinder,重写BindModel方法:

public class DecimalModelBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var v = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            decimal parsedValue = 0m;
            if (!decimal.TryParse(v.AttemptedValue, out parsedValue)) {
                var error = @"'{0}'不是正确的数值格式";
                bindingContext.ModelState.AddModelError(bindingContext.ModelName, string.Format(error, v.AttemptedValue, bindingContext.ModelMetadata.DisplayName));
            }
            return base.BindModel(controllerContext, bindingContext);
        }
    }

      然后在Application_Start事件中注册一下即可:

ModelBinders.Binders.Add(typeof(decimal), new Ichari.Common.MvcExtended.DecimalModelBinder());

说明:此方法只针对后台的Model默认校验,如果启用前台unobtrusive js的话,需要自定义客户端的Validate规则,也可参考文章:http://greenicicleblog.com/2011/02/28/fixing-non-localizable-validation-messages-with-javascript/

原文地址:https://www.cnblogs.com/qiuliang/p/2563953.html