gpt4 book ai didi

asp.net-mvc - 禁用 'The value ' xxx' 对 'yyy' 消息无效

转载 作者:行者123 更新时间:2023-12-04 06:51:04 24 4
gpt4 key购买 nike

在我的 ASP.NET MVC 应用程序中,我有一个表单并且我正在使用 ViewModel,因此 ModelBinder 可以绑定(bind)到我的强类型类。我正在使用 DataAnnotations 进行验证

public class FormViewModel
{
[Required]
public string SomeValue {get;set;}

[Range(0, 10, ErrorMessage="Enter a number between 0 and 10.")]
public byte? SomeOtherValue {get;set;}

}

这很好用。然而,问题是当用户没有为 SomeOtherValue 输入有效值(如 abc)时,会弹出标准 MVC 错误:“值‘abc’对‘SomeOtherValue’无效”。这真的很烦人,因为我无法自定义此消息。我知道有多种方法可以本地化此消息,但这没有意义(我不想要一般消息,我想要特定值的值)。

我尝试将 RegularExpression 属性应用于“SomeOtherValue”,它只允许字节值,但标准验证可能会“覆盖”此验证。有没有办法为属性应用自定义“值无效”消息,或者以其他方式禁用标准消息?

最佳答案

如果自定义验证属性不适合您,这里有一个不同的(非理想方式,恕我直言)来修复它。在 Controller 中:

if (!ModelState.IsValid)
{
string fieldName = "ThatFieldName";
var m = ViewData.ModelState[fieldName];

if (m != null && m.Errors.Count > 0)
{
ViewData.ModelState.Remove(fieldName);
ViewData.ModelState.AddModelError(fieldName, "You mucked that field up.");
}
}

关于asp.net-mvc - 禁用 'The value ' xxx' 对 'yyy' 消息无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9610822/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com