这是一个片段:
public class OrderItemModel
{
public int ID { get; set; }
public decimal Quantity { get; set; }
}
public class OrderMenuModel : List<OrderItemModel>, IValidatableObject
{
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield return new ValidationResult("test");
}
}
[HttpPost]
public ActionResult Calculate(OrderMenuModel menuItems)
{
if (!TryValidateModel(menuItems))
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
// processing
}
Validate()
方法未自动调用,因此我必须调用TryValidateModel()
。由于这确实有帮助,我认为我的OrderMenuModel
没有任何问题。此外,当类的实例是包含对象的成员时,它可以工作,如下所示:
public class OrderModel : IValidatableObject
{
public OrderMenuModel MenuItems { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
// validation without calling MenuItems.Validate(), as it gets called automatically
}
}
[HttpPost]
public ActionResult Place(OrderModel order)
{
// no need to call TryValidateModel()
}
有人能弄清楚第一种情况会发生什么吗?感谢。