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"

Jack G
  • 63
  • 2
  • 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,142
  • 8
  • 26
  • I would prefer not to write this line: [Display (Name = "Email" Resource Type = typeof (Resources.Strings))] just this: public string Email { get; set; } – Jack G Oct 18 '13 at 13:50
  • OK, what are your thoughts on the other option - the custom attribute? – Matt Griffiths Oct 18 '13 at 14:48
  • I do not like that I have to remember to specify the attribute in all fields. Surprising that it can not be done smarter. – Jack G Oct 18 '13 at 22:54
  • But it may be I will have to take the alternative. How is it done? – Jack G Oct 18 '13 at 22:55