IValidateObject how to clear / Reset ModelState.IsValid

I have a class that implements IValidateObject. My business rule is executed after completing additional work in the controller action. The problem I have is ModelState.IsValid, still false. I am trying to find how to reset this or retry to update ModelState. I tried TryUpdateModel, which ran the Validate method, and if I go through my rule it will now be valid, but ModelState.IsValid is still false (and I see that it still complains 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 } } 
+4
source share
1 answer

I do not see the point in this. You have a controller action that receives user input that you manually straighten if not valid and want to check if the model is valid or not. If you manually fixed it, why are you testing again? You know what it will really be, right? What is the point of writing a validation rule that you redefine?

Also note that everything that you fix under the influence of the POST controller (for example, updating the model property) must be accompanied by ModelState.Remove("TheKeyOfThePropertyYouHaveManuallyUpdated") so that these changes manually have some effect.

+3
source

Source: https://habr.com/ru/post/1348179/


All Articles