Ali*_*hşi 6 asp.net-mvc localization data-annotations asp.net-mvc-4
模型
[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; }
}
Run Code Online (Sandbox Code Playgroud)
视图
@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>
}
Run Code Online (Sandbox Code Playgroud)
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
资源文件

产量

RequiredAttribute本地化工作,但LocalizedDisplayNameAttribute不起作用.我找不到任何解决方案来解决这个问题.
有什么建议,遗失在哪里?
Dar*_*rov 24
你好像用这个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; }
}
Run Code Online (Sandbox Code Playgroud)
至于为什么你的车轮改造不起作用,好吧,不能肯定地说.为什么要关心什么时候你可以摆脱它.
| 归档时间: |
|
| 查看次数: |
11727 次 |
| 最近记录: |