Get member to which attribute was applied from inside attribute constructor?

后端 未结 3 1448
遇见更好的自我
遇见更好的自我 2020-11-30 10:11

I have a custom attribute, inside the constructor of my custom attribute I want to set the value of a property of my attribute to the type of the property my attribute was a

3条回答
  •  情深已故
    2020-11-30 10:51

    You can do next. It is simple example.

    //target class
    public class SomeClass{
    
        [CustomRequired(ErrorMessage = "{0} is required", ProperytName = "DisplayName")]
        public string Link { get; set; }
    
        public string DisplayName { get; set; }
    }
        //custom attribute
        public class CustomRequiredAttribute : RequiredAttribute, IClientValidatable
    {
        public string ProperytName { get; set; }
    
        public IEnumerable GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var propertyValue = "Value";
            var parentMetaData = ModelMetadataProviders.Current
                 .GetMetadataForProperties(context.Controller.ViewData.Model, context.Controller.ViewData.Model.GetType());
            var property = parentMetaData.FirstOrDefault(p => p.PropertyName == ProperytName);
            if (property != null)
                propertyValue = property.Model.ToString();
    
            yield return new ModelClientValidationRule
            {
                ErrorMessage = string.Format(ErrorMessage, propertyValue),
                ValidationType = "required"
            };
        }
    }
    

提交回复
热议问题