views:

709

answers:

2

Hello! I have a localized application, and I am wondering if it is possible to have the DisplayName for a certain model property set from a Resource.

I'd like to do something like this:

public class MyModel {
  [Required]
  [DisplayName(Resources.Resources.labelForName)]
  public string name{ get; set; }
}

But I can't to it, as the compiler says: "An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type" :(

Are there any workarounds? I am outputting labels manually, but I need these for the validator output!

+5  A: 

How about writing a custom attribute:

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

    private static string GetMessageFromResource(string resourceId)
    {
        // TODO: Return the string from the resource file
    }
}

which could be used like this:

public class MyModel 
{
    [Required]
    [LocalizedDisplayName("labelForName")]
    public string Name { get; set; }
}
Darin Dimitrov
Yes, I worked on a similar solution this morning and it it feasible. Then I found this post which has the same approach: http://adamyan.blogspot.com/2010/02/aspnet-mvc-2-localization-complete.html
Palantir
A: 

The difference between the solution proposed here and the solution in the link proposed by Palantir is that this one use one Resource file for all the entities. The second use a Resource for each entity.

Bugeo