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!");
}
@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);
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With