首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET MVC 範例專案「Suteki.Shop」分析:自訂資料驗證機制

     編輯:關於ASP.NET

專案實作 IValidatingBinder 介面與 ValidatingBinder 類別,擴充預設模型綁定並整合驗證邏輯:

public virtual void UpdateFrom(BindingContext bindingContext) {
  foreach (var property in bindingContext.Target.GetType().GetProperties()) {
    try {
      foreach (var binder in propertyBinders)
        binder.Bind(property, bindingContext);
    } catch (Exception ex) {
      if (ex.InnerException is FormatException || ex.InnerException is IndexOutOfRangeException) {
        AddModelError(property, bindingContext, "Invalid value for {0}".With(property.Name));
      } else if (ex is ValidationException) {
        AddModelError(property, bindingContext, ex.Message);
      } else if (ex.InnerException is ValidationException) {
        AddModelError(property, bindingContext, ex.InnerException.Message);
      } else throw;
    }
  }
  if (!bindingContext.ModelStateDictionary.IsValid)
    throw new ValidationException("Bind Failed. See ModelStateDictionary for errors");
}

驗證類別圖

透過 propertyBinders 集合針對各屬性套用驗證規則(如 Required、Range、Regex),錯誤自動寫入 ModelState,Controller 僅需檢查 ModelState.IsValid。展示了乾淨的驗證與模型綁定分離設計。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved