When should I use Modelstate.Isvalid?

Asked

Viewed 3,777 times

8

When should I use the ModelState.isValid? Is it only in the insertion of data? And in the case of update and delete? We need?

1 answer

12


The verification of the validity of ModelState should be done every time a form is sent. Not only for inserts, edits and exclusions.

The ModelState not only serves to Models, but also for Viewmodels. The essential function of ModelState is to represent the validity of what was sent to Controller and, in case of non-validity, also detail the errors, if applicable (ModelState.Errors).

Thus, all the work of checking the fill and values of each property of the sent object is done alone. You just need to insert the decor appropriately into the Model or Viewmodel.

  • Gypsy, assuming I tried to validate a business rule in the backend and that validation failed. The right (or more common) is to add the error message in the modelstate with Modelstate.Adderror? Today I simply launch an Exception and show it on an Alert bootstrap...

  • 1

    ModelState.AddModelError is the right way. Exceptions are slow and characterize systemic failures, not validation failures, which are expected flows in the functioning of the system.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.