是否有一种强有力的方法来删除ASP.NET MVC中的ModelState错误

时间:2012-12-23 04:15:52

标签: asp.net-mvc modelstate

有没有办法在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");

3 个答案:

答案 0 :(得分:26)

这是我的解决方案 - 在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);
 }

答案 1 :(得分:4)

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

答案 2 :(得分:0)

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

        for (int i = 0; i < Input.ClubInfo?.Count; i++)
        {
            ModelState.Remove("Input.ClubInfo[" + i + "].Membershipnr2");
        }