Home > database >  Different labels for instances of properties typed by the same class within the same view model
Different labels for instances of properties typed by the same class within the same view model

Time:11-15

I am trying to get a page rendered with different labels like this:

Tool details: ______________ //Description follows the label

Hardware details: _______ //Description follows the label

View:

@model MyViewMode
@MyHelperFor(c => c.Tool.Description)
@MyHelperFor(c => c.Hardware.Description)

View model:

public class MyViewMode
{
    public SubPropertiesVM Tool { get; set; } = new Tool ();
    public SubPropertiesVM Hardware { get; set; } = new Hardware ();
}

public class SubPropertiesVM
{
    public int ID { get; set; }
    public string Description { get; set; }
    public string SubPropertyLabel { get; set; }
}

If I let the system default to the property name, then I would get the same label for all instances.

I could decorate Description in the SubPropertiesVM class [DisplayName("Some label")], but then, again, the same text "Some label" would be rendered twice in the page.

I thought of assigning a different value to SubPropertyLabel upon each initialization, and then somehow make Razor utilize it. But, my understanding is that [DisplayName("")] does not take a variable as a parameter.

My helper has an optional parameter, and sets it as the label. That does work fine. However, each view model is used in several views. I would prefer not to manually and repetitively set the label on each view, but set it only once for each view model.

Is it possible to set in MyViewModel the label texts for properties in SubPropertiesVM?

CodePudding user response:

You could initialize the properties when you create them, like this:

public SubPropertiesVM Tool { get; set; } = new Tool ()
{
    Description = "Tool",
    SubPropertyLabel = "ToolLabel"
};

Do the same for Hardware property, of course with another description etc.

Then Tool and Hardware will get different descriptions.

  • Related