Reputation: 9463
I have a class that implements IValidateObject. My business rule is satisfied after I do some additional work in a controller's action. The problem I have is the ModelState.IsValid is still false. I am trying to find how to have it reset or rerun so the ModelState is updated. I tried TryUpdateModel, that trigged the Validate method and if I step through my rule is now valid, but ModelState.IsValid is still false (and I can see it is still complaining about the same rule).
[HttpPost]
public ActionResult Create(MyModel model)
{
//ModelState.IsValid is False at this point
//model.Do More Stuff To Satisfy IValidateObject rule. At this point all my rules are valid
TryUpdateModel(model); // <-- If run TryUpdateModel and step through, I can see my rule is valid
if (ModelState.IsValid) // this is still False
{
//Save
}
}
Update:
I ended up calling
ModelState.Clear();
[HttpPost]
public ActionResult Create(MyModel model)
{
//model.Do More Stuff To Satisfy IValidateObject rule. At this point all my rules are valid
ModelState.Clear();
TryUpdateModel(model);
if (ModelState.IsValid)
{
//Save
}
}
Upvotes: 4
Views: 4515
Reputation: 1039298
I don't see the point of this. You have a controller action which receives user input that you are manually rectifying if not valid and willing to test afterwards whether the model is valid or not. If you have manually rectified it why are you testing once again? You know it will be valid, don't you? What's the point of writing a validation rule that you are overriding?
Also note that everything that you rectify at hand in a POST controller action (like updating a model property) should be followed by a ModelState.Remove("TheKeyOfThePropertyYouHaveManuallyUpdated")
so that those manual changes have some effect.
Upvotes: 4