Is there a strongly-named way to remove ModelState errors in ASP.NET MVC

后端 未结 3 1294
一向
一向 2020-12-06 10:33

Is there a way to remove ModelState errors during an ASP.NET MVC postback without having to write each one by hand.

Let\'s say we have a checkbox Billing Same

3条回答
  •  孤街浪徒
    2020-12-06 11:15

    Here's my solution - a RemoveFor() extension method on ModelState, modelled after MVC HTML helpers:

        public static void RemoveFor(this ModelStateDictionary modelState, 
                                             Expression> expression)
        {
            string expressionText = ExpressionHelper.GetExpressionText(expression);
    
            foreach (var ms in modelState.ToArray())
            {
                if (ms.Key.StartsWith(expressionText + "."))
                {
                    modelState.Remove(ms);
                }
            }
        }
    

    Here's how it's used :

    if (model.CheckoutModel.ShipToBillingAddress == true) 
    {
        // COPY BILLING ADDRESS --> SHIPPING ADDRESS
        ShoppingCart.ShippingAddress = ShoppingCart.BillingAddress;
    
        // REMOVE MODELSTATE ERRORS FOR SHIPPING ADDRESS
        ModelState.RemoveFor(x => x.CheckoutModel.ShippingAddress);
    }
    
    if (ModelState.IsValid) 
    {
         // should get here now provided billing address is valid
    }
    

    If anybody can see a way to improve it (or not have to specify the generic type argument) then please let me know. Or if this exists in MvcFutures under a different name I'd rather switch to that.

    While I'm at it here's a helper to check if ModelState is valid for a certain 'tree'

        public static bool IsValidFor(this TModel model,
                                                         System.Linq.Expressions.Expression> expression,
                                                         ModelStateDictionary modelState)
        {
            string name = ExpressionHelper.GetExpressionText(expression);
    
            return modelState.IsValidField(name);
        }
    

    Which can be used like this :

     if (model.IsValidFor(x => x.CheckoutModel.BillingAddress, ModelState))
     {
         _debugLogger.Log("Billing Address Valid", () => ShoppingCart.BillingAddress);
     }
    

提交回复
热议问题