在模型验证中使用来自控制器的 ActionMethod
Using ActionMethod from controller in model validation
我有一个从控制器返回的预留天数列表。我想在模型验证中比较它们。在数据已保留时给出错误。
ReservationController.cs
[HttpGet]
public List<string> GetReservedDays()
{
[...]
return reserved_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);
}
}
}
如何让 GetReservedDays() 在模型中工作?
我在网上发现,基于数据库数据的验证应该在控制器中执行。
在 Create() 方法中,我通过以下方式进行验证并给出错误:
ModelState.AddModelError("StartOfReservation", "ERROR MESSAGE");
我有一个从控制器返回的预留天数列表。我想在模型验证中比较它们。在数据已保留时给出错误。
ReservationController.cs
[HttpGet]
public List<string> GetReservedDays()
{
[...]
return reserved_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);
}
}
}
如何让 GetReservedDays() 在模型中工作?
我在网上发现,基于数据库数据的验证应该在控制器中执行。
在 Create() 方法中,我通过以下方式进行验证并给出错误:
ModelState.AddModelError("StartOfReservation", "ERROR MESSAGE");