简体   繁体   中英

Error inherit generic class MVC

I'm implementing a class which i want to inherit it from interface and class. It is working perfect when i use simple class but i want to make it generic. It is giving error when i made it generic. I'm sharing my code please guide me.

[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]


public abstract class ValidateCheckBox<TEntity, Validate, IValidate>
    where TEntity : class
    where Validate :
    ValidationAttribute
    where IValidate : IClientValidatable
{
    public int MinValue { get; set; }

    public ValidateCheckBox(int minValue)
    {
        MinValue = minValue;
        ErrorMessage = "At least " + MinValue + " {0} needs to be checked.";
    }

    public override string FormatErrorMessage(string propName)
    {
        return string.Format(ErrorMessage, propName);
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        try
        {
            List<CheckboxInfo> valueList = (List<CheckboxInfo>)value;
            foreach (var valueItem in valueList)
            {
                if (valueItem.Selected)
                {
                    return ValidationResult.Success;
                }
            }
            return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
        }
        catch (Exception x)
        {
            return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
        }
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule
        {
            ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
            ValidationType = "minchecked",
        };

        rule.ValidationParameters["minvalue"] = MinValue;

        yield return rule;
    }
}

The issue that is causing the error is that you are not inheriting from ValidationAttribute. You're using it as a constraint. See MSDN on constraints . But that brings up other problems. I don't think generic attributes are supported. See this and this .

I think the way you're going to have to use this is the plain ol':

public abstract class ValidateCheckBox : ValidationAttribute { ... }

It looks like there is a workaround by adding properties of Object to your custom attribute and specifying the generic type when using the attribute:

public class GenericClass<T>
{ ... }

public class CustomAttribute : Attribute
{
    public System.Object info;
}

And then using it like this:

[CustomAttribute(info = typeof(GenericClass<...>))]
...

More info about the workaround here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM