An object reference is required for the non-static field, method, or property error when passing parameter to attribute

964 views Asked by At

In my MVC project, i want to validate an input by other input value. For instance according by following code, it doesn't return validation message if employee is a female and user doesn't choose any military service value but if employee is male, it returns validation message but i am getting this error during the runtime;

"An object reference is required for the non-static field, method, or property HRManager.Models.Employee.CheckMilitary()"

public class Employee
{
    public string Firstname { get; set; }
    public string Lastname { get; set; }
    public int Gender { get; set; }

    [RequiredByValue(IsRequired = CheckMilitary())]
    public string MilitaryService { get; set; }

    private bool CheckMilitary()
    {
        // If gender is female return false
        return (this.Gender == 0)? false : true;
    }
}

public class RequiredByValue : ValidationAttribute
{
    public bool IsRequired { get; set; }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        //todo
        return base.IsValid(value, validationContext);
    }
}
1

There are 1 answers

2
Shane On

It looks like you are calling a non static property from a static method. You will need to either make the CheckMilitary static, or create an instance of Employee

seems like you are trying to determine if the gender and thus make the MilitaryService field required before you know the 'Employee`

give us an example on how and when you are calling: HRManager.Models.Employee.CheckMilitary() and I'll give you proper example on how to fix.