0

Current code in model:

[Display(Name = "E-mail")]
public string EMail { get; set; }

Desired code:

public string EMail { get; set; }

I would like to delegate the translation to a handler, something like this:

if(propertyName == "EMail") return "E-mail"

user484204
  • 63
  • 1
  • 8

1 Answers1

0

Based on my understanding of your question, I'm assuming that you are trying to implement localisation in your application.

If so, there are two options;

Resources

In .NET you can add Resource (.resx) files into your application to handle translation (one resx for each language). Then you can specify the Resource by specifying the ResourceType property of your Display attribute. For example;

public class Model
{
  [Display(Name = "Email", ResourceType = typeof(Resources.Strings))]
  public string Email { get; set; }
}

Custom attribute

Alternatively, if you are set on implementing this in a handler then you could implement a custom attribute, as demonstrated in this question.

Edit: Modified from the example in the above post.

If you add a new Resource file to your project - say Strings.resx and add "HelloWorld" as a field. You can then create a new attribute, such as LocalisedDisplayNameAttribute;

public class LocalisedDisplayNameAttribute : DisplayNameAttribute
{
  public LocalisedDisplayNameAttribute(string resourceId)
    : base(GetMessageFromResource(resourceId))
  {
  }

  private static string GetMessageFromResource(string resourceId)
  {
    // "Strings" is the name of your resource file.
    ResourceManager resourceManager = Strings.ResourceManager;
    return resourceManager.GetString(resourceId);
  }
}

You can then use it as follows;

public class Model
{
  [LocalisedDisplayName("HelloWorld")]
  public string Email { get; set; }
}

Let me know if I can help further,

Matt

Community
  • 1
  • 1
Matt Griffiths
  • 1,122
  • 8
  • 26