zielony, it's a flow control issue. I can not remember the exact sequence ...
I am assuming that you are creating a new book.
ModelState.IsValid is a read only property. If someone else sets it for you to invalid, you are out of luck.
Line 6 of your example code. ModelState.AddModelError will also set ModelState.IsValid to false.
Have you read these tutorials at http://www.asp.net/learn/mvc/?:
#18 | Performing Simple Validation View in VB or C#
#19 | Validating with the IDataErrorInfo Interface View in VB or C#
#20 | Validating with a Service Layer View in VB or C#
#21 | Validation with the Data Annotation Validators View in VB or C#
#21 is the newest of these tutorials. You'll find different approaches in each tutorial.
#19 has an interesting comment:
"DateReleased value is validated automatically. Because the DateReleased property does not accept NULL values, the DefaultModelBinder generates a validation error for this property automatically when it does not have a value. If you want to modify the error message for the DateReleased property then you need to create a custom model binder."
You may find help here:
http://www.hanselman.com/blog/SplittingDateTimeUnitTestingASPNETMVCCustomModelBinders.aspx
#18 talks about "Prebinding Validation and Postbinding Validation":
"There are actually two types of validation error messages – those generated before the HTML form fields are bound to a class and those generated after the form fields are bound to the class."
http://odetocode.com/Blogs/scott/archive/2009/04/27/12788.aspx
"6 Tips for ASP.NET MVC Model Binding"
http://odetocode.com/Blogs/scott/archive/2009/05/05/12801.aspx
"Iterating on an ASP.NET MVC Model Binder"
http://msdn.microsoft.com/en-us/magazine/dd942838.aspx
"Building Testable ASP.NET MVC Applications"
http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/03/17/a-better-model-binder.aspx
http://stephenwalther.com/blog/archive/2009/02/25/asp.net-mvc-tip-49-use-the-linqbinarymodelbinder-in-your.aspx
For more links, use Google: asp.net mvc custom model binder
Regards,
Gerry (Lowry)
P.S.:
Interesting is: http://www.codeplex.com/FluentValidation
and http://fluentvalidation.codeplex.com/Wiki/View.aspx?title=mvc
"Integration with ASP.NET MVC"
Gerry Lowry, Principal
Ability Business Computer Services ~~ Because it's your Business, our Experience Counts!
68 John W. Taylor Avenue
Alliston · Ontario · Canada · L9R 0E1 · gerry.lowry@abilitybusinesscomputerservices.com
Websites:
http://abilitybusinesscomputerservices.comhttp://gerrylowryprogrammer.com ~~
résumé & testimonials
http://veganoccasions.com ~~ recipes