【问题标题】:Change the default error message in the model state binder - not working更改模型状态绑定器中的默认错误消息 - 不起作用
【发布时间】:2022-09-23 11:18:41
【问题描述】:

这就是 mvc.net core 3.1 - 这就是我的财产在课堂上的样子

[BindProperty]
[Required(ErrorMessage = \"Enter the valid amount\")]
[ValidDecimal(ErrorMessage = \"Enter the amount correctly\")]
public decimal? QuoteAmountTotal { get; set; }

自定义有效十进制值的代码是

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
public class ValidDecimalAttribute : ValidationAttribute{
protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
{
    if (value == null || value.ToString().Length == 0)
    {
        return ValidationResult.Success;
    }

    return decimal.TryParse(value.ToString(), out _) ? ValidationResult.Success : new ValidationResult(ErrorMessage);
}

}

我在此字段中输入带有空格或字母数字的值。例如 2 0 0 0。 但是,它显示默认的 mvc.net 核心错误,而不是我的自定义错误,即

值 \'2 0 0 0\' 对于 QuoteAmountTotal 无效。

这是 AttemptedvalueisInvalidAccessor enter image description here

我需要显示我的自定义错误消息,而不是默认的 MVC 错误模型消息,在这种情况下不显示。

    标签: asp.net-core-mvc modelstate custom-errors error-messaging


    【解决方案1】:

    我怎样才能使这些看起来正确的基于 linq 我正在使用错误消息从错误模型集合中获取相关索引,并将我自己的错误消息添加到同一索引中。最后删除旧的 - 以某种方式尝试用我的替换相同的错误消息。

    如何使以下代码高效:

    ModelError customError = new ModelError("My custom error 2");
    

    //Replacing the item at the same index

    ModelState[nameof(QuoteAmountTotal)].Errors.Insert(ModelState[nameof(QuoteAmountTotal)].Errors.IndexOf(ModelState[nameof(QuoteAmountTotal)].Errors.Single(x => x.ErrorMessage.Contains("is not valid for"))), mI);
    

    //Deleting the old one

    ModelState[nameof(QuoteAmountTotal)].Errors.RemoveAt(ModelState[nameof(QuoteAmountTotal)].Errors.IndexOf(ModelState[nameof(QuoteAmountTotal)].Errors.Single(x => x.ErrorMessage.Contains("is not valid for"))));
    

    请帮忙,谢谢

    【讨论】:

      【解决方案2】:

      如果你在 IsValid 方法上放一个断点,当你调试时,你会发现该方法永远不会被执行

      正如doc 所示:

      模型状态表示来自两个子系统的错误:模型绑定和模型验证。源自模型绑定的错误一般是数据转换错误。模型验证发生在模型绑定之后,并在数据不符合业务规则时报告错误。

      更新: 您可以尝试用您的客户模型绑定器替换模型绑定器,我尝试如下:

      public class SomeEntityBinder : IModelBinder
          {
              public Task BindModelAsync(ModelBindingContext bindingContext)
              {
                  if (bindingContext == null)
                  {
                      throw new ArgumentNullException(nameof(bindingContext));
                  }
      
      
      
                 var modelName = bindingContext.ModelName;
                  // Try to fetch the value of the argument by name
                  var valueProviderResult = bindingContext.ValueProvider.GetValue(modelName);
      
      
      
                 if (valueProviderResult == ValueProviderResult.None)
                  {
                      return Task.CompletedTask;
                  }
      
      
      
                 bindingContext.ModelState.SetModelValue(modelName, valueProviderResult);
                  var value = valueProviderResult.FirstValue;
      
      
      
                 // Check if the argument value is null or empty
                  if (string.IsNullOrEmpty(value))
                  {
                      return Task.CompletedTask;
                  }
                  
                  if (!decimal.TryParse(value, out var QuoteAmountTotal))
                  {
                      // Non-decimal arguments result in model state errors
                      bindingContext.ModelState.TryAddModelError(modelName,"Enter the amount correctly");
      
      
      
                     return Task.CompletedTask;
                  }
                  bindingContext.Result = ModelBindingResult.Success(QuoteAmountTotal);
                  return Task.CompletedTask;
              }
          }
      

      在模型中:

      [ModelBinder (typeof(SomeEntityBinder))]
      public decimal QuoteAmountTotal { get; set; }
      

      结果:

      【讨论】:

      • 没错,它永远不会被执行,它是在添加到它之前的方式,我只需要用我的错误替换错误 - 可能与错误字典有关。
      • 如何使错误捕获我的自定义错误消息?
      • 我已经更新了我的答案,请检查一下
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-04
      • 1970-01-01
      • 1970-01-01
      • 2018-12-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多