【问题标题】:ASP.NET MVC 2 Numeric value validationASP.NET MVC 2 数值验证
【发布时间】:2010-09-14 19:35:43
【问题描述】:

我在一个类上有这个属性:

public virtual decimal? Number { get; set; }

当我在表单上使用它时,MVC 会自动验证它。如果用户输入一个字母,自然会返回错误:

“数值 'D' 对 Number 无效。”

如何更改此类错误消息甚至控制该行为?我没有找到相关的属性或类似的东西。

谢谢!

【问题讨论】:

    标签: asp.net-mvc-2 data-annotations


    【解决方案1】:

    它实际上不是来自模型验证的消息。当模型绑定器无法将输入值转换为绑定属性的值类型时,该消息将添加到模型状态。例如,当绑定的属性是整数并且用户在该属性的输入字段中输入了非数字字符时,可能会发生这种情况。

    不幸的是,要覆盖该消息,您必须以“硬”方式进行,即扩展 DefaultModelBinder 类并覆盖 SetProperty 方法。这是一个例子:

    public class MyModelBinder: DefaultModelBinder
    {
        public MyModelBinder()
        {
        }
    
        protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value)
        {
            string key = bindingContext.ModelName + "." + propertyDescriptor.Name;
            if (bindingContext.ModelState[key] != null)
            {
    
                foreach (ModelError error in bindingContext.ModelState[key].Errors)
                {
                    if (IsFormatException(error.Exception))
                    {
                        bindingContext.ModelState[key].Errors.Remove(error);
                        bindingContext.ModelState[key].Errors.Add(string.Format("My message for {0}.", propertyDescriptor.DisplayName));
                        break;
                    }
                }
            }
            base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);
        }
    
        private bool IsFormatException(Exception e)
        {
            while (e != null)
            {
                if (e is FormatException)
                {
                    return true;
                }
                e = e.InnerException;
            }
            return false;
        }
    }
    

    【讨论】:

      【解决方案2】:

      简单地使用给定的范围验证器funda,你会得到你想要的

      对于任何数字验证,您必须根据您的要求使用不同的不同范围验证:

      对于整数

      [Range(0, int.MaxValue, ErrorMessage = "Please enter valid integer Number")]
      

      浮动

      [Range(0, float.MaxValue, ErrorMessage = "Please enter valid float Number")]
      

      双倍

      [Range(0, double.MaxValue, ErrorMessage = "Please enter valid doubleNumber")]
      

      【讨论】:

      • @fedorui 感谢您的编辑。这会更容易理解。但它有用吗?
      猜你喜欢
      • 1970-01-01
      • 2010-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-21
      相关资源
      最近更新 更多