ASP.NET MVC: Is Data Annotation Validation Enough?

后端 未结 5 841
暗喜
暗喜 2020-12-13 02:15

I\'m using the Data Annotation validation extensively in ASP.NET MVC 2. This new feature has been a huge time saver, as I\'m now able to define both client-side validation

5条回答
  •  情深已故
    2020-12-13 03:19

    The DataAnnotation is certainly not enough. I use it extensively also to pre-validate my calls to the domain model to get better error reporting and fail as early as possible.

    You can however tweak the DataAnnotation Model yourself to ensure properties with [Required] MUST be posted. (will follow up with code later today).

    UPDATE Get the source for DataAnnotations Model Binder and find this line in DataAnnotationsModelBinder.cs

    // Only bind properties that are part of the request
    if (bindingContext.ValueProvider.DoesAnyKeyHavePrefix(fullPropertyKey)) {
    

    Change it to

    // Only bind properties that are part of the request
    bool contextHasKey = bindingContext.ValueProvider.DoesAnyKeyHavePrefix(fullPropertyKey);
    bool isRequired = GetValidationAttributes(propertyDescriptor).OfType().Count() > 0;
    if (contextHasKey || (!contextHasKey && isRequired)) {
    

提交回复
热议问题