[英]Change the default error message in the model state binder - not working
這就是 mvc.net core 3.1 - 這就是我的財產在 class 中的樣子
[BindProperty]
[Required(ErrorMessage = "Enter the valid amount")]
[ValidDecimal(ErrorMessage = "Enter the amount correctly")]
public decimal? QuoteAmountTotal { get; set; }
自定義 ValidDecimal 值的代碼是
[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在此處輸入圖像描述
我需要顯示我的自定義錯誤消息,而不是默認的 MVC 錯誤 model 消息,在這種情況下不顯示。
如果在 IsValid 方法上設置斷點,當你調試時,你會發現該方法永遠不會被執行
正如文檔所示:
Model state 表示來自兩個子系統的錯誤:model 綁定和 Z20F35E630DAF44DBFA4ZC3F6D8 驗證。 model綁定產生的錯誤一般是數據轉換錯誤。Model驗證發生在model綁定后,數據不符合業務規則時報錯。
如何使這些看起來正確 linq 基於我正在使用錯誤消息從 Errors Model 集合中獲取相關索引,並在同一索引處添加我自己的錯誤消息。 最后刪除舊的 - 在某種程度上嘗試用我的替換相同的錯誤消息。
如何使以下代碼高效:
ModelError customError = new ModelError("My custom error 2");
//替換相同索引的item
ModelState[nameof(QuoteAmountTotal)].Errors.Insert(ModelState[nameof(QuoteAmountTotal)].Errors.IndexOf(ModelState[nameof(QuoteAmountTotal)].Errors.Single(x => x.ErrorMessage.Contains("is not valid for"))), mI);
//刪除舊的
ModelState[nameof(QuoteAmountTotal)].Errors.RemoveAt(ModelState[nameof(QuoteAmountTotal)].Errors.IndexOf(ModelState[nameof(QuoteAmountTotal)].Errors.Single(x => x.ErrorMessage.Contains("is not valid for"))));
請幫忙,謝謝
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.