Search code examples
asp.net-mvcasp.net-mvc-4localizationdata-annotations

Dataannotations localization


model

[MetadataType(typeof(UserMetaData))]
public class User
{
    public int Id { get; set; }
    public string UserName { get; set; }
}

public class UserMetaData
{
    public int Id { get; set; }

    [Required(ErrorMessageResourceType = typeof(Resources.ModelValidation), ErrorMessageResourceName = "UserNameRequired")]
    [LocalizedDisplayNameAttribute("UserName", NameResourceType = typeof(Resources.ModelValidation))]
    public string UserName { get; set; }
}

view

@using (Html.BeginForm())
{
    <div>
        @Html.LabelFor(x => x.UserName)
        @Html.TextBoxFor(x => x.UserName)
        @Html.ValidationMessageFor(x => x.UserName)
    </div>
    <div>
        <input type="submit" value="Gönder" />
    </div>
}

LocalizedDisplayNameAttribute

public class LocalizedDisplayNameAttribute : DisplayNameAttribute
{
    private PropertyInfo _nameProperty;
    private Type _resourceType;

    public LocalizedDisplayNameAttribute(string displayNameKey)
        : base(displayNameKey)
    { }

    public Type NameResourceType
    {
        get { return _resourceType; }
        set
        {
            _resourceType = value;
            //initialize nameProperty when type property is provided by setter  
            _nameProperty = _resourceType.GetProperty(base.DisplayName, BindingFlags.Static | BindingFlags.Public);
        }
    }
    public override string DisplayName
    {
        get
        {              
            //check if nameProperty is null and return original display name value  
            if (_nameProperty == null) { return base.DisplayName; }
            return (string)_nameProperty.GetValue(_nameProperty.DeclaringType, null);
        }
    }
}

resource file

enter image description here

output

enter image description here

RequiredAttribute localization works, but LocalizedDisplayNameAttribute does not work. I cant find any solution to fix this.

Any suggestion, where is the missing?


Solution

  • You seem to be reinventing the wheels with this LocalizedDisplayNameAttribute attribute. This functionality is already built into the framework, right into the [Display] attribute that you could use directly:

    public class UserMetaData
    {
        public int Id { get; set; }
    
        [Required(ErrorMessageResourceType = typeof(Resources.ModelValidation), ErrorMessageResourceName = nameof(Resources.ModelValidation.UserNameRequired)]
        [Display(ResourceType = typeof(Resources.ModelValidation), Name = nameof(Resources.ModelValidation.UserName))]
        public string UserName { get; set; }
    }
    

    As far as why your wheel reinvention doesn't work, well, can't say for sure. Why care when you could get rid of it anyways.