Naveed Ahmed
Naveed Ahmed

Reputation: 10386

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?

Upvotes: 5

Views: 15200

Answers (4)

Mohamad Elnaqeeb
Mohamad Elnaqeeb

Reputation: 563

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

Upvotes: 2

Spencer Sullivan
Spencer Sullivan

Reputation: 575

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
}

Upvotes: 1

KyleMit
KyleMit

Reputation: 29889

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
}

Upvotes: 1

Shyju
Shyju

Reputation: 218722

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

Upvotes: 6

Related Questions