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>
}
本地化显示名称属性
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);
}
}
}
资源文件
output
requiredAttribute 本地化有效,但 LocalizedDisplayNameAttribute 无效。我找不到任何解决方案来解决这个问题。
有什么建议吗,缺失在哪里?
你似乎正在用这个重新发明轮子LocalizedDisplayNameAttribute
属性。此功能已内置于框架中,直接内置于[Display]
您可以直接使用的属性:
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; }
}
至于为什么你的轮子重塑不起作用,嗯,不能肯定地说。当你无论如何都可以摆脱它时为什么要关心它呢?
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)