14

有没有办法在 ASP.NET MVC 回发期间删除 ModelState 错误,而无需手动编写每个错误。

假设我们有一个复选框Billing Same As Shipping,然后我们希望在ShippingAddress选中它时忽略用户写的任何内容 - 通常您可能会这样做。

ModelState.Remove("Checkout.ShipppingAddress.FirstName");
ModelState.Remove("Checkout.ShipppingAddress.LastName");
ModelState.Remove("Checkout.ShipppingAddress.Address1");
ModelState.Remove("Checkout.ShipppingAddress.Address2");
...
ModelState.Remove("Checkout.ShipppingAddress.ZipCode");
4

3 回答 3

29

这是我的解决方案 -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);
 }
于 2012-12-23T04:26:09.623 回答
4

如果这是针对MVC 6的,建议使用ModelBindingHelper.ClearValidationStateForModel(Type, ModelStateDictionary, IModelMetadataProvider, string).

于 2015-09-19T21:47:48.597 回答
0

Asp core 2.2 剃须刀页面。删除 Input.ClubInfo 类型列表中的嵌套对象 modelstate(onpost) 错误。

        for (int i = 0; i < Input.ClubInfo?.Count; i++)
        {
            ModelState.Remove("Input.ClubInfo[" + i + "].Membershipnr2");
        }
于 2019-12-02T11:57:51.503 回答