这是我的解决方案 -RemoveFor()
上的扩展方法ModelState
,仿照 MVC HTML 助手:
public static void RemoveFor<TModel>(this ModelStateDictionary modelState,
Expression<Func<TModel, object>> expression)
{
string expressionText = ExpressionHelper.GetExpressionText(expression);
foreach (var ms in modelState.ToArray())
{
if (ms.Key.StartsWith(expressionText + "."))
{
modelState.Remove(ms);
}
}
}
这是它的使用方法:
if (model.CheckoutModel.ShipToBillingAddress == true)
{
// COPY BILLING ADDRESS --> SHIPPING ADDRESS
ShoppingCart.ShippingAddress = ShoppingCart.BillingAddress;
// REMOVE MODELSTATE ERRORS FOR SHIPPING ADDRESS
ModelState.RemoveFor<SinglePageStoreModel>(x => x.CheckoutModel.ShippingAddress);
}
if (ModelState.IsValid)
{
// should get here now provided billing address is valid
}
如果有人能找到改进它的方法(或者不必指定泛型类型参数),请告诉我。或者,如果它以不同的名称存在于 MvcFutures 中,我宁愿切换到该名称。
当我在这里时,这里有一个助手来检查 ModelState 是否对某个“树”有效
public static bool IsValidFor<TModel, TProperty>(this TModel model,
System.Linq.Expressions.Expression<Func<TModel, TProperty>> expression,
ModelStateDictionary modelState)
{
string name = ExpressionHelper.GetExpressionText(expression);
return modelState.IsValidField(name);
}
可以这样使用:
if (model.IsValidFor(x => x.CheckoutModel.BillingAddress, ModelState))
{
_debugLogger.Log("Billing Address Valid", () => ShoppingCart.BillingAddress);
}