如何为动态生成的表单自定义默认错误消息“值''无效”

问题描述 投票:0回答:1

我是 ASP.NET Core 新手。我有一个动态生成的表单。我希望验证错误消息是

"The value must be numeric"
而不是我得到

"The value 'a' is invalid."

这是我的视图模型:

[RegularExpression("^[0-9]*$", ErrorMessage = "The value must be numeric")]
public List<int> Units_Service { get; set; }

这是我的表单代码:

for (int i = 0; i < Model.Workload_Category_Name.Count; i++)
{
   <div class="row">
       <div class="col-md-3">
           <b><u>  @Html.DisplayFor(model => model.Workload_Category_Name[i])</u> </b>
       </div>
       <div class="col-md-4">
          @Html.TextBoxFor(model => model.Units_Service[i], new { style = "width: 15%", MaskedTextBox = "9999" })
          @Html.ValidationMessageFor(model => model.Units_Service[i])
       </div>
   </div>
 }

尽管事实上,我已将自定义错误消息放入视图模型中,如上所示,但我仍然收到默认消息

"The value '' is invalid"
。请问这种情况有什么解决办法吗?

c# asp.net-core kendo-asp.net-mvc
1个回答
0
投票

问题在于,在您的正则表达式有机会执行其操作之前,模型绑定就会失败。模型绑定器抛出您看到的错误。

尝试将属性更改为

string
列表,然后在需要时转换回整数。

[RegularExpression("^[0-9]*$", ErrorMessage = "The value must be numeric")]
public List<string> Units_Service { get; set; }


List<int> convertedToInts = _model.Units_Service.Select(v => int.Parse(v)).ToList();
© www.soinside.com 2019 - 2024. All rights reserved.