Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.net MVC nested model display name

I have my model like below:

Model:

public class Farm
{
    public Animal Cow1 {get;set;}
    public Animal Pig1 {get;set;} 
}

public class Animal
{
    [DisplayName("Animal Name")]
    public string Name {get;set;}
}

View:

@Html.LabelFor(m => m.Cow1.Name)
@Html.LabelFor(m => m.Pig1.Name)

My problem is:

Instead of "Animal Name", I want Cow1's name label to be "Cow Name" and Pig1's name label to be "Pig Name".

Is it possible to do so? Thanks.


Thanks to @devqon, the suggestion can solve my problem. Yet may I ask more about doing it from the attribute? Like below, is there something like the attribute "DisplayMetaData" behave?

public class Farm
{
    [DisplayMetaData(typeof(CowMetaData))]
    public Animal Cow1 {get;set;}

    [DisplayMetaData(typeof(PigMetaData))]
    public Animal Pig1 {get;set;} 
}

public class Animal
{
    [DisplayName("Animal Name")]
    public string Name {get;set;}
}

public class CowMetaData
{
    [DisplayName("Cow Name")]
    public string Name {get;set;}
}

public class PigMetaData
{
    [DisplayName("Pig Name")]
    public string Name {get;set;}
}

I want the code to be written this way like the way we use the attribute [MetadataType], that the MetaData are defined in a seperate class, and that the display name can still be used by the HtmlHelper LabelFor function. But [MetadataType] is only used for classes but not property, so I come up with the question.

Any help is appreciated.

like image 649
Chai Avatar asked May 17 '26 15:05

Chai


1 Answers

Could you not rework your classes to implement inheritance to solve the problem? For example:

public abstract class Animal
{
    public abstract string Name { get; set; }
}

public class Cow : Animal
{
    [Display(Name="Cow Name")]
    public override string Name { get; set; }
}

public class Pig : Animal
{
    [Display(Name = "Pig Name")]
    public override string Name { get; set; }
}

public class Farm
{
    public Cow Cow { get; set; }
    public Pig Pig { get; set; }
}
like image 102
chris Avatar answered May 20 '26 03:05

chris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!