Asp.net-Mvc
數據註釋本地化
模型
[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> }本地化顯示名稱屬性
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 不起作用。我找不到任何解決方案來解決這個問題。
任何建議,失踪在哪裡?
您似乎正在使用此
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; } }至於為什麼你的車輪改造不起作用,好吧,不能肯定地說。無論如何,當你可以擺脫它時,為什麼要關心它。

