【发布时间】:2012-03-30 05:37:56
【问题描述】:
我收到The value 'abc' is not valid for fieldName. 作为错误消息。这是默认错误消息,我想以更简单的方式覆盖它。
截至目前,我尝试过的内容列在下面
[RegularExpression(@"^\d+$",ErrorMessage="enter numeric value")][Integer(ErrorMessageResourceType = typeof(appName.Resources.abc.Resource), ErrorMessageResourceName = "error_numeric")][RegularExpression("([1-9][0-9]*)")]-
Range(1,int.max,ErrorMessage="enter numeric value")
但未能更改默认错误消息。
建议我最简单的方法来做到这一点。using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; using System.Web.Mvc; namespace blueddPES.ViewModels { public class ContactViewModel { [Integer(ErrorMessage="sdfdsf")] public int? hp { get; set; } }
【问题讨论】:
-
不要寻找数据注释来覆盖此验证场景。您将无法使用整数等值类型来实现这一点,正如我在您的上一个问题中已经回答的那样:stackoverflow.com/questions/9921067/…。您需要自定义模型绑定器,因为它是将请求值解析为整数的默认模型绑定器,如果失败,它会添加默认错误消息,该消息在 System.Web.Mvc 程序集中硬编码为资源。
-
但是@DarinDimitrov 我不想为这个小东西添加那么多自定义代码。除了添加自定义模型绑定器,我还有另一个选项可以将字符串作为数据类型而不是 int。
-
是的,你确实有这个选项。
标签: asp.net asp.net-mvc-3 data-annotations