Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a ASP .NET MVC model value to validate another model value?

I have a model class like this:

public class SomeClass
{
    public int EmployeeId {get;set;}
    public int DayTotal {get;set}
}

For this model class I am creating a custom ValidationAttribute for the 'DayTotal' property. The custom validator will check the entered value 'DayTotal' value against another table that defines the maximum days allowed.

How to I refer to the selected 'EmployeeId' from the Create view when writing my query in the validator?

public class DayTotalAttribute : ValidationAttribute
{
    ProjectDBContext db = new ProjectDBContext();

    public override bool IsValid(object value)
    {
        if (value == null)
        {
            return false;
        }

        var products = from p in db.EmployeeDayMax
                       where p.EmployeeId = ???
    }
}

UPDATE:

My solution has taken a different approach. The helpful answers got me looking in other places. This blog from Scott Gu helped to provide a simpler approach:

In my model ->

   public class SomeClass : IValidateObject
   {
         public int EmployeeId {get; set;}
         public int DayTotal {get; set;}

         public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
         {
            ProjectDBContext db = new ProjectDBContext();
            //check maxes...can refer directly to EmployeeId in LINQ queries
            if(failed)
            {
               yield return new ValidationResult("Days have been maxed!");
            }
like image 799
John M Avatar asked Feb 16 '11 17:02

John M


2 Answers

@Luke Bennett is completely right, ValidationContext is new in MVC 3.

Here's an example using your code:

public class DayTotalAttribute : ValidationAttribute
{
    ProjectDBContext db = new ProjectDBContext();

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value != null)
        {
            var model = (SomeClass)validationContext.ObjectInstance;
            var products = from p in db.EmployeeDayMax
                       where p.EmployeeId = model.EmployeeId

            bool somethingIsWrong = // do your validation here

            if (somethingIsWrong)
            {
                return ValidationResult("Error Message");
            }
        }

        return base.IsValid(value, validationContext);
    }    
}
like image 192
fretje Avatar answered Oct 02 '22 15:10

fretje


In .NET 4.0 there is another overload for IsValid that takes a ValidationContext parameter. This has an ObjectInstance property which you can cast to SomeClass and gives you access to its other properties.

like image 38
Luke Bennett Avatar answered Oct 02 '22 14:10

Luke Bennett