Home > other >  Using ActionMethod from controller in model validation
Using ActionMethod from controller in model validation

Time:04-01

I have a list of reserved days returned from controller. I want to compare them in Model validation. To give error while data is already reserved.

ReservationController.cs

 [HttpGet]
    public List<string> GetReservedDays()
    {

       [...]

        return reserved_days;

    }

I want to use these days

ReservationModel.cs

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        var property = new[] { "EndOfReservation" };
        if (EndOfReservation < StartOfReservation)
        {
            yield return new ValidationResult("End must be after start", property);
        }

       var reservedDays = GetReservedDays(); //   Error CS0103  The name 'GetReservedDays' does not exist in the current context Reservation2  

        foreach(var day in reservedDays)
        {
            if(StartOfReservation < day && day < EndOfReservation)
            {
                yield return new ValidationResult("This date is reserved", property);
            }
        }

    }

How to get GetReservedDays() working in model?

CodePudding user response:

I found on the Internet that validations based on data from the database should be performed in the controller.

In Create() method i make validation and give error by:

ModelState.AddModelError("StartOfReservation", "ERROR MESSAGE");
  • Related