[SOLVED] Remove ModelState errors in ASP.NET MVC

Issue

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

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

Answered By – Shyju

Answer Checked By – Timothy Miller (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *