如何在 MVC 中更改由 @Html 助手生成的“数据验证编号"消息验证 [英] How to change 'data-val-number' message validation in MVC while it is generated by @Html helper
问题描述
假设这个模型:
Public Class Detail
...
<DisplayName("Custom DisplayName")>
<Required(ErrorMessage:="Custom ErrorMessage")>
Public Property PercentChange As Integer
...
end class
和视图:
@Html.TextBoxFor(Function(m) m.PercentChange)
将继续这个 html:
will proceed this html:
<input data-val="true"
data-val-number="The field 'Custom DisplayName' must be a number."
data-val-required="Custom ErrorMessage"
id="PercentChange"
name="PercentChange" type="text" value="0" />
我想自定义 data-val-number
错误消息,我猜这是因为 PercentChange
是一个 Integer
.我一直在寻找这样的属性来更改它,range
或任何相关的都不起作用.
我知道有机会编辑不显眼的 js 文件本身或在客户端覆盖它.我想像服务器端的其他人一样更改 data-val-number
的错误消息.
I want to customize the data-val-number
error message which I guess has generated because PercentChange
is an Integer
. I was looking for such an attribute to change it, range
or whatever related does not work.
I know there is a chance in editing unobtrusive's js file itself or override it in client side. I want to change data-val-number
's error message just like others in server side.
推荐答案
这并不容易.默认消息作为嵌入资源存储在 System.Web.Mvc
程序集中,并且正在获取的方法是内部密封内部类 (System.Web.Mvc) 的私有静态方法.ClientDataTypeModelValidatorProvider+NumericModelValidator.MakeErrorString
).就好像微软编码的那个人隐藏了一个最高机密:-)
This is not gonna be easy. The default message is stored as an embedded resource into the System.Web.Mvc
assembly and the method that is fetching is a private static method of an internal sealed inner class (System.Web.Mvc.ClientDataTypeModelValidatorProvider+NumericModelValidator.MakeErrorString
). It's as if the guy at Microsoft coding this was hiding a top secret :-)
你可以看看下面的博客文章 描述了一个可能的解决方案.您基本上需要将现有的 ClientDataTypeModelValidatorProvider 替换为一个定制的.
You may take a look at the following blog post which describes a possible solution. You basically need to replace the existing ClientDataTypeModelValidatorProvider with a custom one.
如果你不喜欢你需要做的硬核编码,你也可以在你的视图模型中用一个字符串替换这个整数值,并在它上面有一个自定义验证属性,它会进行解析并提供一个自定义错误消息(甚至可以本地化).
If you don't like the hardcore coding that you will need to do you could also replace this integer value inside your view model with a string and have a custom validation attribute on it which would do the parsing and provide a custom error message (which could even be localized).
这篇关于如何在 MVC 中更改由 @Html 助手生成的“数据验证编号"消息验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!