Override dataType mismatch message of property in

2019-07-12 02:21发布

问题:

want to override datetime "wrong format message". i.e by default DateTime property display message:: The value '12--2002' is not valid for * dateTime PropertyName: (DD/MM/YYYY). But i want this message to display through some Resource file.

 public class candidateAddressViewModel
 { [Required(ErrorMessageResourceType = typeof(myApp.Resources.res.Resource),
          ErrorMessageResourceName = "error_format")]
   [Display(Name = "lived_from", ResourceType = typeof(myApp.Resources.res.Resource)), DisplayFormat(DataFormatString = "{0:dd-MM-yy}", ApplyFormatInEditMode = true)]
    public DateTime? dateTimePropertyName{ get; set; }
 } 

Suggest me easiest possible way.

回答1:

Create a resource file in App_Global_Resources (for example "Messages.resx". Add two strings:

PropertyValueInvalid (Value {0} for {1} is invalid.)

PropertyValueRequired. (Field {0} is required.)

In your Global.asax add:

DefaultModelBinder.ResourceClassKey = "Messages";