When to check and when not to check ModelState.IsValid
I'm using ASP.NET MVC2. I love how I can annotate my model's fields and check ModelState.IsValid.
The obvious reason to check it is when doing validation, but should you always check it in case new validation rules are applied to the model? That way you don't forget / need to check whether the controller checks IsValid.
Is there some reason not to do this check in all cases? Maybe just when the controller action has side-effects (DB-writing etc)?
but should you always check it in case new validation rules are applied to the model?
You should do this check always else you end up persisting models that don't have valid state.
Generally, in asp.net-mvc, models passed to actions are view models, and they contain all and only data needed for action to act. If that data is invalid, theoretically it should be impossible for action to do its job.
ModelState.IsValid ensures that all data needed for action is in good state, ready to be acted on. I do not see reason where you would not want to validate that data.
You should always check if the model is valid immediately before attempting to use the data collected in the model to do something. That's the purpose of validation in the first place.
It looks obvious to mention, but i will give it a shot. There is NO need to check model state when you are NOT posting your model. The common scenarios are when you are getting your data from service and displaying on a get action.