Henrique Moreira
Henrique Moreira

Reputation: 93

asp net mvc - have a model attribute reference another model attribute

I would like to add 'Price' on class B as reference to 'Price' on class A. I want to avoid the repetition of the declaration of a property:

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 
}

So, for example, if in class A i want to change the range i don't want to have to remember which other classes have the same property.

Upvotes: 0

Views: 451

Answers (2)

Steve
Steve

Reputation: 11963

you can define a constant for this

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

....


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

Or you can inherit the Range attribute like

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

then you can just do

[MyRange]

and when you want to change the value just change it inside MyRangeAttribute.cs

Upvotes: 0

MistyK
MistyK

Reputation: 6222

What about inheritance?

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 
}

Upvotes: 1

Related Questions