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
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.