專案實作 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。展示了乾淨的驗證與模型綁定分離設計。