asp.net-mvc - 在 ASP.NET MVC 3 中自定义模型绑定(bind)错误消息

标签 asp.net-mvc validation asp.net-mvc-3 model-binding fluentvalidation

我正在使用带有 Fluent Validation 的 ASP.NET MVC 3。我希望我的所有错误消息的措辞和格式都相同,无论它们是验证错误消息还是模型绑定(bind)错误消息。

假设我有以下 View 模型:

[Validator(typeof(PersonValidator))]
public class Person
{
    [ScaffoldColumn(false)] public int    Id   { get; set; }
                            public string Name { get; set; }
                            public int    Age  { get; set; }
}

要使用 Fluent Validation 验证这一点,我可能会使用如下内容:
public class EditorValidator : AbstractValidator<EditorModel>
{
    public EditorValidator()
    {
        RuleFor(model => model.Month.Value).InclusiveBetween(0, 120)
    }
}

如果用户为 Age 输入“abc” ,这会导致模型绑定(bind)错误,而不是验证错误。这是因为 "abc"不是 int .系统甚至不会询问“abc”是否在 0 和 120 之间,因为“abc”不能存储在 Age 中。 .

这很好,也很有意义。问题是生成的错误消息是:

The field Age must be a number.



我希望消息的格式和措辞与 Fluent Validation 产生的其他错误消息一样。在这种情况下,我想:

'Age' must be a number.



我意识到这只是一个细微的区别,但我想控制模型绑定(bind)错误消息。

如何自定义模型绑定(bind)错误消息以匹配 Fluent Validation 使用的错误消息?

最佳答案

我不确定是否有其他方法可以做到这一点,但我使用 Data Annotations Extensions ,也可以通过 NuGet (Install-Package DataAnnotationsExtensions.MVC3) 获得这种确切类型的东西。这个包裹会给你一个IntegerAttribute ,然后您可以从那里指定一条错误消息,如下所示:

[Integer(ErrorMessage = "'Age' must be a number.")]
public int Age { get; set; }

关于asp.net-mvc - 在 ASP.NET MVC 3 中自定义模型绑定(bind)错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6488124/

相关文章:

qt - 禁用 QSpinBox 中的验证

c# - 无法加载文件或程序集 'Newtonsoft.Json'

asp.net-mvc - 为什么我的 Razor 助手没有在 Using 语句中执行?

ASP.NET (MVC) 路由国际化

Jquery验证: How To Ignore Placeholder Text (Produce Error on Default/Blank)

asp.net-mvc - 自定义 ValidationAttribute 中的访问 Controller 上下文

c# - 谁能建议一些有用的教程来开发umbraco网站?

c# - 在模型属性 MVC4 ASP.NET 中处理动态内容

jquery - 从 MVC4 中的 @Html.ValidationSummary() 中删除项目符号

asp.net-mvc - 将 javascript 文件存储在与 ASP.NET Core 1.1 中的 View 相同的文件夹中?