【发布时间】:2017-12-04 12:18:11
【问题描述】:
我制作了一个餐厅预订表,其中要求提供餐厅名称、用餐日期和人数。
我有一个预订班级,其中有一个 ID、餐厅 ID、日期和人数:
public class Booking
{
public int Id { get; set; }
public int IDRestaurant{ get; set; }
[CustomPlaceValidator]
public int Nbpeople { get; set; }
[CustomDateValidator]
public DateTime Date { get; set; }
}
还有一个Resto类,它有一个ID、一个名字、一个电话号码和一个号码表:
public class Resto
{
public int Id { get; set; }
[Required(ErrorMessage = "Le nom du restaurant doit être saisi")]
public string Nom { get; set; }
[Display(Name = "Téléphone")]
[RegularExpression(@"^0[0-9]{9}$", ErrorMessage = "Le numéro de téléphone est incorrect")]
public string Telephone { get; set; }
[Range(0, 9999)]
public int Size { get; set; }
}
我想对每个新预订进行验证,以确认餐厅未满。 为此,在验证预订的“人数”字段时,我需要“餐厅名称”字段的值和“日期”字段的值,然后检索该餐厅在该日期的所有预订,并检查人数之和是否远低于餐厅的容量。
public class CustomPlaceValidator : ValidationAttribute
{
private IDal dal = new Dal();
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
int nb = 0;
if (dal.GetAllBooking() != null)
{
foreach (var booking in dal.GetAllBooking())
nb += booking.Nbpeople;
if (nb ..... ) return ValidationResult.Success;
return new ValidationResult("The restaurant is full for this date.");
}
return ValidationResult.Success;
}
}
(这是草稿,测试显然没有完成)
我怎样才能获得其他属性的价值来进行验证?
【问题讨论】:
-
如果您想要需要访问数据库的客户端验证,请使用
RemoteAttribute进行 ajax 调用 - How to: Implement Remote Validation in ASP.NET MVC。不要将数据库访问代码放在ValidationAttribute
标签: c# asp.net-mvc validation validationattribute