Wednesday, August 21, 2013

C# Get Localized Display Annotation without object instance

If you use an annotation on a model property like this:

[Display(ResourceType = typeof(MyLocalization.CommonModelsStrings), Name = "User_LastName")]
public string LastName { getset; }


Elsewhere you can access the localized display string of the model class without instantiating it using the following method. I put it in a static helper class named ModelAnnotationsUtils for easy access:

public static string GetLocalizedDisplay<TModel>(string pPropertyName)
{
 DisplayAttribute attribute = ((DisplayAttribute)(typeof(TModel).GetProperty(pPropertyName).GetCustomAttributes(typeof(DisplayAttribute), true)[0]));
 ResourceManager rm = new ResourceManager(attribute.ResourceType);
 return rm.GetString(attribute.Name);
}

Usage:

string lastName = ModelAnnotationsUtils.GetLocalizedDisplay<Model.User>("LastName");

No comments: