亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

自定義驗證屬性的 ValidationContext 缺少字段

自定義驗證屬性的 ValidationContext 缺少字段

C#
青春有我 2023-08-13 16:07:20
我正在使用 MVC 5。我正在編寫一個表單,供用戶向內部應用程序提交索賠,并且在創建索賠時,我需要根據用戶的當前余額驗證用戶的索賠金額。如果金額大于余額(例如 10 美元對 5 美元),它會拒絕,并要求他們將余額清零。我認為最好將余額作為CurrentBalance視圖模型上的(不可編輯的)屬性,并使用自定義驗證屬性來比較兩個值。我將其呈現為表單上的只讀字段。當用戶選擇要提交到哪個程序(例如 HRA)時,ajax 請求會根據他們選擇的程序填寫當前余額。問題在于,當視圖模型實例作為我的屬性的一部分傳遞時ValidationContext,它CurrentBalance?始終顯示為零。所以無論余額是多少,驗證無一例外都會失敗。我嘗試CurrentBalance在視圖上創建一個普通的非只讀字段,并在提交之前自行設置值。我還嘗試在渲染視圖之前在控制器中設置值。無論哪種情況,它仍然為零,如上圖所示。我的自定義屬性如下:public class ClaimAmountAttribute : ValidationAttribute{? ? protected override ValidationResult IsValid(object value, ValidationContext validationContext)? ? {? ? ? ? var claim = (ClaimCreateViewModel)validationContext.ObjectInstance;? ? ? ? var amount = (decimal)value;? ? ? ? if (claim.CurrentBalance - amount < 0)? ? ? ? {? ? ? ? ? ? return new ValidationResult(GetErrorMessage());? ? ? ? }? ? ? ? return ValidationResult.Success;? ? }? ? public string GetErrorMessage() => "Amount must be less than balance; please zero out balance instead.";}以下是我觀點的相關部分 - 不過,只讀屬性是否存在似乎并沒有什么區別:@model ClaimCreateViewModel<div class="form-group">? ? @Html.LabelFor(model => model.CurrentBalance, htmlAttributes: new { @class = "control-label col-md-2" })? ? <div class="col-md-10">? ? ? ? @Html.EditorFor(model => model.CurrentBalance, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })? ? </div></div><div class="form-group">? ? @Html.LabelFor(model => model.Amount, htmlAttributes: new { @class = "control-label col-md-2" })? ? <div class="col-md-10">? ? ? ? @Html.EditorFor(model => model.Amount, new { htmlAttributes = new { @class = "form-control" } })? ? ? ? @Html.ValidationMessageFor(model => model.Amount, "", new { @class = "text-danger" })? ? </div></div>似乎我所做的一切都沒有產生 的CurrentBalance價值ValidationContext。請幫幫我。
查看完整描述

1 回答

?
米琪卡哇伊

TA貢獻1998條經驗 獲得超6個贊

事實證明,我的 POST 操作的屬性[Bind]丟失了CurrentBalance。驗證發生在操作之前,但這并不重要;[Bind]在此之前采取行動,以防止過度發布。我已經更新了該操作,現在可以使用了:


public ActionResult Create([Bind(Include = "TransactionID,Amount,CurrentBalance")] ClaimCreateViewModel claim)

    // ...

}


查看完整回答
反對 回復 2023-08-13
  • 1 回答
  • 0 關注
  • 122 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號