2

I need to load the DisplayName for a property dynamically (from a database). For example something like this:

[DisplayName(getDescriptionForLanguage("test"))]
public string test{ get; set; }

But it's only possible to load a DisplayName dynamically, only constants are allowed. Is there some way to get the DisplayName as result of a method and NOT from a Resourcefile or a constant?

Obl Tobl
  • 5,604
  • 8
  • 41
  • 65
  • Where is the DisplayNameAttribute used? Can you change the code there? – dtb Aug 19 '13 at 09:55
  • AFAIK DisplayName is used at compliation so it has to be constant http://stackoverflow.com/a/9434934/1714342 – Kamil Budziewski Aug 19 '13 at 09:55
  • possible duplicate of [DisplayAttribute name with a variable, Dynamic DisplayName](http://stackoverflow.com/questions/9434918/displayattribute-name-with-a-variable-dynamic-displayname) – Kamil Budziewski Aug 19 '13 at 09:56
  • Related: http://stackoverflow.com/questions/356464/localization-of-displaynameattribute – dtb Aug 19 '13 at 09:56

2 Answers2

2

It's possible to call a method that returns a non-constant string.
You have to create a new Attributclass, for example like this:

class DisplayNameLanguage : DisplayNameAttribute
{
    private readonly string resourceName;
    public DisplayNameLanguage(string resourceName)
        : base()
    {
        this.resourceName = resourceName;
    }

    public override string DisplayName
    {
        get
        {
            return getDescriptionForLanguage(resourceName);
        }
     }
}

Now you have to create a partial subclass of your model. There you can use the new Attribute that gets the description from your method getDescriptionForLanguage:

[MetadataType(typeof(TestMD))]
public partial class Test { }
public partial class TestMD
{
    [DisplayNameLanguage("Test")]
    public string Prop1 { get; set; }
}
Obl Tobl
  • 5,604
  • 8
  • 41
  • 65
0

There is no way to change that behavior. The value passed to the attribute needs to be a compile-time constant, meaning that even using a static property of a static class won't do the trick.

As suggested by dtb you could however stop using the DisplayName-attribute to get the display name and instead build your own mechanism at the place where the value of the DisplayName-attribute is being evaluated.

Spontifixus
  • 6,570
  • 9
  • 45
  • 63