繁体   English   中英

ASP Net MVC-具有模型属性引用另一个模型属性

[英]asp net mvc - have a model attribute reference another model attribute

我想在类B上添加“价格”作为对类A上的“价格”的引用。我想避免重复声明属性:

public class A{

    // ... stuff 

    [Required]
    [Display(Name = "Price (Euros)")]
    [Range(1, 1000)]
    public float Price { get; set; }

    // ... more stuff 
}

public class B{

    // ... stuff 

    [Required]
    [Display(Name = "Price (Euros)")]
    [Range(1, 1000)]
    public float Price { get; set; }

    // ... more stuff 
}

因此,例如,如果在A类中我想更改范围,则我不想记住其他哪些类具有相同的属性。

那继承呢?

public class A{

    // ... stuff 
    [Required]
    [Display(Name = "Price (Euros)")]
    [Range(1, 1000)]
    public float Price { get; set; }

    // ... more stuff 
}

public class B : A{

    // ... stuff 

    // ... more stuff 
}

您可以为此定义一个常量

public static class Constants
{
    public const int PriceMin = 1;
    public const int PriceMax = 1000;
}

....


[Range(Constants.PriceMin, Constants.PriceMax)]

或者您可以继承Range属性,例如

public class MyRangeAttribute : RangeAttribute
{
    public MyRangeAttribute()
       :base(1, 1000)
    {
    }
}

那你就可以做

[MyRange]

当您想更改值时,只需在MyRangeAttribute.cs中进行更改

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM