Search code examples
asp.net-mvcmodelstate

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


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 As Shipping and we want to then ignore anything user wrote for ShippingAddress when it's checked - typically what you might do is this.

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");

Solution

  • If this is for MVC 6, suggest using ModelBindingHelper.ClearValidationStateForModel(Type, ModelStateDictionary, IModelMetadataProvider, string).