MVC 中的“data-val-number"消息验证由@Html helper 生成时如何更改 [英] How to change 'data-val-number' message validation in MVC while it is generated by @Html helper

查看:25
本文介绍了MVC 中的“data-val-number"消息验证由@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:

   <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 中的“data-val-number"消息验证由@Html helper 生成时如何更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆