【发布时间】:2013-05-30 13:41:05
【问题描述】:
型号
[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 无效。我找不到任何解决方案来解决这个问题。
有什么建议,缺的在哪里?
【问题讨论】:
-
我没有这个!为什么要扩展 DysplayNameAttr?此控件支持作为 Requerid 的本地化!
-
@Fals,我不明白。你能解释一下吗? DisplayAttribute 不支持本地化
-
是的,当您提供 ResourceType 属性时,Name 就是 resourceName!
标签: asp.net-mvc asp.net-mvc-4 localization data-annotations