Is it correct way to use ModelState.Remove to deal with ModelState?

后端 未结 5 838
挽巷
挽巷 2020-12-05 14:17

Im working on a big MVC3 web application and have an annoyance regarding the ModelState.IsValid method.

ModelState is being used in nearly all of my con

5条回答
  •  暖寄归人
    2020-12-05 14:58

    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 + ".") || ms.Key == expressionText)
                {
                    modelState.Remove(ms);
                }
            }
        }
    

    Here's how it's used :

    if (model.CheckoutModel.ShipToBillingAddress == true) 
    {
        // REUSE BILLING ADDRESS FOR SHIPPING ADDRESS
        ShoppingCart.ShippingAddress = ShoppingCart.BillingAddress;
    
        // REMOVE MODELSTATE ERRORS FOR SHIPPING ADDRESS
        ModelState.RemoveFor(x => model.CheckoutModel.ShippingAddress);
    }
    

    So in answer to your question I believe there are definitely use-cases where this is the right way to do it, and a strongly typed helper like this makes it much nicer to look at - and easier to justify if you're concerned about lots of magic strings.

提交回复
热议问题