Chai
Chai

Reputation: 31

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.

Upvotes: 3

Views: 835

Answers (2)

HamedH
HamedH

Reputation: 3273

I think this is reasonable:

public class Farm
{
    [DisplayName("Cow")]
    public Animal Cow1 {get;set;}

    [DisplayName("Pig")]
    public Animal Pig1 {get;set;} 
}

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

and use this in cshtml (I wonder asp was able to automatically do this):

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

Upvotes: 0

chris
chris

Reputation: 111

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; }
}

Upvotes: 1

Related Questions