如何为两个属性创建验证属性 MVC


public class Product
{
    public int Id { get; set; }
    [Required(ErrorMessage = "Please enter name")]
    [StringLength(60, MinimumLength = 2)]
    [Remote("ValidateProductName", "Products", ErrorMessage = "Product with this name already exist")]
    public string Name { get; set; }
    [Required(ErrorMessage = "Please enter price")]
    [Range(0.1, double.MaxValue, ErrorMessage = "Price must be greater than 0")]
    public decimal Price { get; set; }
    [Required(ErrorMessage = "Please enter quantity")]
    [DataType(DataType.Currency)]
    //[Range(0, int.MaxValue, ErrorMessage = "The value must be greater than 0")]
    public int Quantity { get; set; }
    [Required(ErrorMessage = "Please enter date")]
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
    //[DateRange("01/01/2050")]
    [CurrentDate(ErrorMessage = "You enter invalid data")]
    public DateTime DeliveryDate { get; set; }
    [Required(ErrorMessage = "Please enter if is in promotion")]
    public bool InPromotion { get; set; }
}

我想检查数量倍数价格是否大于100 000,如果大于写入错误消息。我需要使用属性。有人可以帮我吗?

您需要为逻辑定义自定义属性。

public class ValidatePriceAttribute: ValidationAttribute
{
    private double maxVal = 0.0;
    public ValidatePriceAttribute(double maxVal)
    {
       this.maxVal = maxVal;
    }
    protected override ValidationResult IsValid(object value, ValidationContext ctx)
    {
        var obj = ctx.ObjectInstance as Product;
        if (obj != null) {
              if( obj.Price * obj.Quantity > this.maxVal){
                     return new ValidationResult("error message goes here");
              }
        } 
       return null;
    }
}

[ValidatePrice(100000.0)]
public double Price {get;set;}

上面的代码只是示例,它需要大量改进以使其更加灵活和通用,我将练习留给您:)

最新更新