是否有一个强命名的方法,以消除在ASP.NET MVC的ModelState错误(Is there

2019-07-17 12:39发布

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

Answer 1:

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



Answer 2:

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


文章来源: Is there a strongly-named way to remove ModelState errors in ASP.NET MVC