Dataannotations本地化 [英] Dataannotations localization

查看:194
本文介绍了Dataannotations本地化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

模式

[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; }
}

查看

@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);
        }
    }
}

资源文件

输出

本地化RequiredAttribute标签的作品,但LocalizedDisplayNameAttribute不起作用。我找不到任何解决方案来解决这个问题。

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

任何建议,其中丢失的?

Any suggestion, where is the missing?

推荐答案

您似乎是重塑这种 LocalizedDisplayNameAttribute 属性车轮。此功能已经内置到框架中,对进入 [显示] 属性,你可以直接使用:

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 = "UserNameRequired")]
    [Display(Name = "UserName", ResourceType = typeof(Resources.ModelValidation))]
    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.

这篇关于Dataannotations本地化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆