开发者

How to set the same parameters for every required attribute

开发者 https://www.devze.com 2023-02-16 15:27 出处:网络
I\'m making localization for my ASP MVC application and I want to set the same settings for every property.

I'm making localization for my ASP MVC application and I want to set the same settings for every property.

for exampl开发者_如何学编程e:

    [Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "RequiredAttribute_ValidationError")]
    [Display(Name = "Hasło")]
    public string Password { get; set; }

Is there any way to do it automatically?


After creating CustomRequiredAttribute you should register your custom attribute in Global.asax

protected void Application_Start()
{
    DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(CustomRequiredAttribute), typeof(RequiredAttributeAdapter));
    ...

source: http://forums.asp.net/t/1528277.aspx


Override the RequiredAttribute and put your implementation details in the constructor i.e.

   public class CustomRequiredAttribute : RequiredAttribute{
       public CustomRequiredAttribute():base(){
           ErrorMessageResourceType = typeof(Resources);
           ErrorMessageResourceName = "RequiredAttribute_ValidationError");
       }
   }

then decorate your property like:

[CustomRequired]
[Display(Name = "Hasło")]
public string Password { get; set; }


You could write a custom attribute deriving from RequiredAttribute and setting those properties:

[MyRequired]
[Display(Name = "Hasło")]
public string Password { get; set; }
0

精彩评论

暂无评论...
验证码 换一张
取 消