如何将一个成员的值限制为<=另一个成员

本文关键字:成员 另一个 一个 | 更新日期: 2023-09-27 18:37:28

我在MVC4中使用实体框架,我有以下域类。

我的问题是,如何将销售价格的值限制为 <= 价格? 我一直在寻找一个合适的属性来做到这一点,但还没有找到。

编辑:

假设一个人在准备提交表单时输入 $20.00 作为价格值,然后他们输入的销售价格为 $25.00。 程序将禁止这样做,因为销售价格不能高于商品价格。 我想知道是否有[Attribute]可以对销售价格强制执行此限制。

public class MedicalProduct
{
    [Key]
    public int ID { get; set; }
    [Required]
    [StringLength(50)]
    public string Name { get; set; }
    [Required]
    [DataType(DataType.Currency)]
    public double Price { get; set; }
    // needs to be less than price.
    [Required]
    [DataType(DataType.Currency)]
    public double SalePrice { get; set; }
    // is a foreign key
    public int BrandID { get; set; }
}

如何将一个成员的值限制为<=另一个成员

我会创建一个自定义ValidationAttribute来完全按照您的要求进行操作。该属性需要要比较的 propety 的名称和 ComparisonType .我在下面创建了一个非常快速的示例:

比较属性

public enum ComparisonType
{
    LessThan,
    LessThanOrEqual,
    Equal,
    GreaterThanOrEqual,
    GreaterThan,
    NotEqual
}
public sealed class ComparisonAttribute : ValidationAttribute
{
    string PropertyToCompare { get; set; }
    ComparisonType Type { get; set; }
    public ComparisonAttribute(string propertyToCompare, ComparisonType type)
    {
        PropertyToCompare = propertyToCompare;
        Type = type;
    }
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (validationContext.ObjectInstance == null || value == null)
            return new ValidationResult("Cannot compare null values");
        PropertyInfo property = validationContext.ObjectType.GetProperty(PropertyToCompare);
        object propertyValue = property.GetValue(validationContext.ObjectInstance, null);
        string errorMessage = "";
        if (value is IComparable)
        {
            int compVal = ((IComparable)value).CompareTo(propertyValue);
            switch (Type)
            {
                case ComparisonType.LessThan:
                    errorMessage = compVal < 0 ? "" : string.Format("{0} is not less than {1}", validationContext.DisplayName, property.Name);
                    break;
                case ComparisonType.LessThanOrEqual:
                    errorMessage = compVal <= 0 ? "" : string.Format("{0} is not less than or equal to {1}", validationContext.DisplayName, property.Name);
                    break;
                case ComparisonType.Equal:
                    errorMessage = compVal == 0 ? "" : string.Format("{0} is not equal to {1}", validationContext.DisplayName, property.Name);
                    break;
                case ComparisonType.GreaterThanOrEqual:
                    errorMessage = compVal >= 0 ? "" : string.Format("{0} is not greater than or equal to {1}", validationContext.DisplayName, property.Name);
                    break;
                case ComparisonType.GreaterThan:
                    errorMessage = compVal > 0 ? "" : string.Format("{0} is not greater than {1}", validationContext.DisplayName, property.Name);
                    break;
                case ComparisonType.NotEqual:
                    errorMessage = compVal != 0 ? "" : string.Format("{0} cannot be equal to {1}", validationContext.DisplayName, property.Name);
                    break;
                default:
                    errorMessage = "";
                    break;
            }
        }
        if (String.IsNullOrEmpty(errorMessage))
            return ValidationResult.Success;
        return new ValidationResult(errorMessage);
    }
}

用法

public class Model
{
    [Comparison("Value2", ComparisonType.LessThanOrEqual)]
    public int Value1 { get; set; }
    public int Value2 { get; set; }
}

您可以考虑将public double SalePrice { get; set; }变成具有支持字段的功能更齐全的属性。然后,您将在允许set SalePrice之前测试 Price 的值。下面是一个快速示例:

private double _salePrice;
public double SalePrice
{
    get { return _salePrice; }
    set
    {
        // only set _salePrice if it's less than
        // or equal to Price
        if(value <= Price)
            _salePrice = value;
    }
}

试一试...

[编辑] - 我看到你稍微改变了问题,所以补充一点,有一个CompareAttribute可以用来验证两个属性(但是,我确定这仅限于字符串值 - 将确认)。另外,看看这个页面,它有一个自定义解决方案,看起来不错,灵活,可能适合你:http://forums.asp.net/t/1924941.aspx。戈拉头 - 00:43 在英国!!