'Remove ModelState errors in ASP.NET MVC

Is there any way to remove model validation for some properties in a Model in ASP.Net MVC6.

I came across this post Is there a strongly-named way to remove ModelState errors in ASP.NET MVC

which suggests using, ModelBindingHelper.ClearValidationStateForModel(Type, ModelStateDictionary, IModelMetadataProvider, string).

But I am unable to find any further help on this.

Can anyone please suggest a working example of removing a model property using ClearValidationStateForModel?



Solution 1:[1]

This should remove the validation errors for the Title property of your CreatePost view model.

[HttpPost]
public ActionResult Create(CreatePost model)  
{
    if (ModelState.IsValid)
    {
      //to do : Save and return something
    }   
    ModelBindingHelper.ClearValidationStateForModel(model.GetType(),
                                              ModelState,MetadataProvider,"Title");        
    return View(model);
}

Also, ModelState.ClearValidationState will also work.

ModelState.ClearValidationState("Title");

EDIT : As per the comment, OP wants to exclude a certain property to be validated based on another property value. This should work fine.

[HttpPost]
public ActionResult Create(CreatePost model)   //CreatePost model
{
    if (model.Type == 1)
    {
        ModelBindingHelper.ClearValidationStateForModel(model.GetType(), 
                                                    ModelState, MetadataProvider, "Title");
    }
    if (ModelState.IsValid)
    {
        // to do : Do useful stuff and return something
    }
    return View(model);
}

Solution 2:[2]

ModelBindingHelper is new to ASP.NET Core 2.0 / MVC6+

If you need to use against previous versions of .NET / ASP.NET, you can do the following per Simon_Weaver's answer on Is there a strongly-named way to remove ModelState errors:

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

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

And 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<SinglePageStoreModel>(x => x.CheckoutModel.ShippingAddress);
}

if (ModelState.IsValid) 
{
     // should get here now provided billing address is valid
}

Solution 3:[3]

I needed for validation to have an exception for a single field in the VM

In the controller, I am doing:

if ("true" == Condition)
{
    ModelState.Remove("KeyName");
}

If "KeyName" was the only error in the ModelState, it will now be true

if (ModelState.IsValid)
{   
    // ModelState.IsValid is true now
}

Solution 4:[4]

For new comers use

ModelState.ClearValidationState("propertyname");
ModelState.MarkFieldValid("propertyname");

If its nested object then use objectname.propertyname.

this works on ASP.Net Core 6.0

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 KyleMit
Solution 3 Spencer Sullivan
Solution 4 Mohamad Elnaqeeb