System.ComponentModel.DataAnnotations.compare vs System.Web.Mvc.Compare
So, looking at the MSDN documentation and doing a literal comparison of the two classes, I noticed both classes are derived from System.ComponentModel.DataAnnotations.ValidationAttribute. In fact, the classes are almost exactly the same. The only notable difference is that the MVC version also implements IClientValidatable which adds the following properties:
- FormatPropertyForClientValidation - (static member) Formats the property for client validation by prepending an asterisk and a dot.
- GetClientValidationRules - Gets a list of compare-value client validation rules for the property using the specified model metadata and controller context.
As for which class you should use, if the model will be directly bound to a view, use the MVC version so that you can take advantage of the client-side validation. However, if you're using ViewModels, you can stick with the ComponentModel class and avoid the unnecessary overhead of the additional properties. Your call!
System.Web.Mvc.CompareAttribute
System.ComponentModel.DataAnnotations.CompareAttribute
Microsoft Connect work-around is:
Posted by GavK on 6/17/2012 at 5:13 AM
I added a full reference to [System.Web.Mvc.Compare(...)] rather than just using [Compare(...)]
Works for me in VS 2012...
Vinney nailed most of it with the exception of which one you should use...
The reason you have a conflict after changing your target framework to 4.5 is because prior to .NET 4.5 there was no CompareAttribute class in the System.ComponentModel.DataAnnotations namespace and the class defined under System.Web.Mvc filled the gap. Therefore, as an example if you were using [Compare]
and [Required]
attributes in your model class prior to updating your target framework you ended up with a conflict when you upgraded.
Assuming you are not using anything else in the System.Web.Mvc
namespace in your model class, you should remove that using
statement and let it rely on the System.ComponentModel.DataAnnotations
namespace. Unobtrusive client-side validation will continue to work exactly as it did before, just as it does for other attributes that you decorate your model's properties with from the same namespace (eg Required
).
If you wish to be explicit about the reference, you can simply add this line:
using CompareAttribute = System.Web.Mvc.CompareAttribute;