tags:

views:

180

answers:

2

Trying to validate models with DataAnnotations but DefaulModelBinder overrides my Required property error messages and never uses my error messages for invalid data entry. Always show 'value' is invalid for 'property name'.

In another question I saw that MVC 2 uses DataAnnotationsModelBinder but I couldn't find any class in MVC 2 binaries. I downloaded the source for MVC futures and changed some source to compile it for .Net 4.0 but although I had success to compile, it has compatability problems and doesn't work as expected.

Any help is aprreciated.

A: 

This is happening because an exception is thrown in the DefaultModelBinder when it tries to cast the input value to the type of the receiving model property.

You can either use string as type for the properties on the receiving model or make a custom Model binder by implementing IModelBinder and handle the validation.

JHurrah
Yes, I know that and my question is exactly this, how can I use DataAnnotationsModelBinder with MVC 2 RTM. DefaultModelBinder doesn't work as expected when I use validation attributes on my model classes.
yang
+3  A: 

Do not try to use the DataAnnotationsModelBinder with MVC 2 RTM. MVC 2 RTM's DefaultModelBinder already contains all of the logic that was present in the DataAnnotationsModelBinder sample.

Levi
Then why doesn't it show the error messages that I specify with [Required] attributes? It shows "x is a required field". And for the invalid types it shows "x is not a valid value for y", all standard default model binder error messages.. Shouldn't it show the error message that I write in [DataType] error message property?
yang
It should, yes. What version of the System.ComponentModel.DataAnnotations is your project referencing? Maybe it's a mismatch between versions
Jab
What do your declarations look like? Can you show us a sample model (with properties) that is not behaving as expected?
Levi