This question already has an answer here:

I'm trying to create a custom validation rule which will check to see if Times overlap in any case, to do this I have the following:

public class TimesheetLogicAttribute : ValidationAttribute
{

    public TimesheetLogicAttribute()
    {
        //this.jobRecords = jobRecords;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var records = value as List<TimesheetJobRec>;

        records = records.OrderBy(r => r.StartTime).ToList();
        DateTime? current = null;

        foreach(var record in records)
        {
            if (record.StartTime > record.FinishTime)
            {
                return new ValidationResult("Finish time is before start time on " + record?.JobNumber);
            }

            if (current == null)
            {
                current = record.FinishTime;
                continue;
            }

            if(record.StartTime < current)
            {
                return new ValidationResult("Time overlapping");
            }
            current = record.FinishTime;
        }

        return ValidationResult.Success;

        //return base.IsValid(value, validationContext);
    }

}

My corresponding model is:

public class TimesheetJobRec : ModelsBase
{
    // Job number stuff needs to go in here.
    [Required]
    public string JobNumber { get; set; }
    public Timesheet Timesheet { get; set; }

    [Required]
    public string WorkDescription { get; set; }

    [Required]
    [DataType(DataType.Time)]
    public DateTime StartTime { get; set; }

    [Required]
    [DataType(DataType.Time)]
    public DateTime FinishTime { get; set; }

    [Required]
    public double LunchTime { get; set; }

    [ReadOnly(true)]
    [Range(0.25, 24)]
    public double Total { get; set; }

}

Then I decorate my view model like this:

  [Display(Name = "Job Records")]
  [TimesheetLogic]
  public IList<TimesheetJobRec> JobRecords { get; set; }

This all works fine and in my validation I receive my item list correctly, the problem occurs when returning a ValidationResult I get the following error on the ASP side of things:

Object reference not set to an instance of an object.

Line 43:                         <th>Total</th>
Line 44:                     </tr>
Line 45:                     @foreach (var item in Model.JobRecords)
Line 46:                     {
Line 47:                         Html.RenderPartial("_JobEditorRow", item);

On Line 45 the error is thrown, in that foreach in my View I am just rendering existing items. I'm not sure what the cause for this is and whether I'm doing validation correctly or not.

Related posts

Recent Viewed