ASP.NET MVC nested model display name

I have my model as shown 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:

Instead of "Animal Name" I want the Cow1 name tag to be "Cow Name" and the Pig1 tag "Pig Name".

Can this be done? Thank.


Thanks to @devqon, a suggestion might solve my problem. But can I read more about how to do this from an attribute? As shown below, is there something like the strong> DisplayMetaData attribute ?

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 in such a way that we use the [ MetadataType ] attribute , that the metadata is defined in a separate class, and that the display name can still be used by the HtmlHelper LabelFor function. But [MetadataType] is only used for classes, not property, so I am asking a question.

Any help is appreciated.

+3


source to share


2 answers


Could you remake 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; }
}

      

+1


source


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'm wondering if asp was able to do this automatically):

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

      

0


source







All Articles