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.

Need Your Help

two docker app container on one nginx

nginx docker containers hhvm

I try to serve 2 web applications that should be powered by hhvm. It is easy to build up one docker image that includes nginx and the default.conf. But now where I will get n apps as microservices ...

Is there an alternative to Task.Delay(0) and Task.FromResult(0)?

c# .net async-await portable-class-library bcl

I am attempting to create a Portable Class Library (.NET 4.5/Silverlight 5/Win Phone 8/WinRT) that takes advantage of the async/await feature set. I found that I need to include the Microsoft.Bcl.A...