Skip to content

Instantly share code, notes, and snippets.

@davybrion
Created September 15, 2012 16:29
Show Gist options
  • Save davybrion/3728692 to your computer and use it in GitHub Desktop.
Save davybrion/3728692 to your computer and use it in GitHub Desktop.
code snippets for "Convention Based Localization With ASP.NET MVC" post
@Html.LabelFor(m => m.SomeProperty)
[Display(ResourceType = typeof(Resources), Name = "ResourceKeyForSomeProperty")]
public string SomeProperty { get; set; }
public class AnnotationsAndConventionsBasedModelMetaDataProvider : DataAnnotationsModelMetadataProvider
{
protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType,
Func<object> modelAccessor, Type modelType, string propertyName)
{
var result = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
if (string.IsNullOrEmpty(result.DisplayName) && containerType != null && propertyName != null)
{
var keyForDisplayValue = string.Format("{0}_{1}", containerType.Name, propertyName);
var translatedValue = Resources.ResourceManager.GetObject(keyForDisplayValue) as string;
if (!string.IsNullOrEmpty(translatedValue))
{
result.DisplayName = translatedValue;
}
}
return result;
}
}
ModelMetadataProviders.Current = new AnnotationsAndConventionsBasedModelMetaDataProvider();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment