Monday 8 February 2010

DisplayNameAttribute Localized

So here is a simple Attribute, extending the DisplayNameAttribute, inspired from a post on stackoverflow


using System;
using System.Linq;
using System.ComponentModel;
using System.Reflection;
using System.Resources;

namespace MvcExtensions.Attributes
{
[AttributeUsage(AttributeTargets.Property AttributeTargets.Field, AllowMultiple = false)]
public class DisplayNameLocalizedAttribute : DisplayNameAttribute
{
public DisplayNameLocalizedAttribute(Type resourceType, string resourceKey)
: base(LookupResource(resourceType, resourceKey)) { }

internal static string LookupResource(Type resourceType, string resourceKey)
{
PropertyInfo property = resourceType.GetProperties().FirstOrDefault(p => p.PropertyType == typeof(System.Resources.ResourceManager));
if (property != null)
{
return ((ResourceManager)property.GetValue(null, null)).GetString(resourceKey);
}
return resourceKey;
}
}
}

An I use it simply like this:


using MvcExtensions.Attributes;
using MyMvc2Rc2TestApp.App_LocalResources;

namespace MyTestMVC2App.Areas.UserManagement.Models
{
public class User
{
[DisplayNameLocalized(typeof(DisplayName), "User_UserName")]
public string UserName { get; set; }
[DisplayNameLocalized(typeof(DisplayName), "User_Password")]
public string Password { get; set; }
[DisplayNameLocalized(typeof(DisplayName), "User_FirstName")]
public string FirstName { get; set; }
[DisplayNameLocalized(typeof(DisplayName), "User_LastName")]
public string LastName { get; set; }
[DisplayNameLocalized(typeof(DisplayName), "User_Email")]
public string Email { get; set; }
}
}

I have a DisplayName.resx file in App_LocalResources, it is an Embedded Resource with Public Access Modifier

2 comments:

  1. This is good to put your strings in a resource file. How to add localisation in case you support multiple cultures?

    ReplyDelete
  2. Just add a resource per culture and it will use the culture of your thread.

    ReplyDelete