NopCommerce 自定义DataAnnotation DisplayAttribute
NopCommerce 自定义DataAnnotation DisplayAttribute<div id="cnblogs_post_body">System.dll(.Net Framework 4.0 )中已有DisplayNameAttribute 定义,被该标签注释的Model属性,在View中使用Html.LabelFor便可获取设置的字段名称。
namespace System.ComponentModel{ // 摘要: // 指定属性、事件或不采用任何参数的公共 void 方法的显示名称。 public class DisplayNameAttribute : Attribute { // 摘要: // 指定 System.ComponentModel.DisplayNameAttribute 的默认值。此字段为只读。 public static readonly DisplayNameAttribute Default; // 摘要: // 初始化 System.ComponentModel.DisplayNameAttribute 类的一个新实例。 public DisplayNameAttribute(); // // 摘要: // 使用显示名称初始化 System.ComponentModel.DisplayNameAttribute 类的新实例。 // // 参数: // displayName: // 显示名称。 public DisplayNameAttribute(string displayName); // 摘要: // 获取属性、事件或不采用此特性中存储的任何参数的公共 void 方法的显示名称。 // // 返回结果: // 显示名称。 public virtual string DisplayName { get; } // // 摘要: // 获取或设置显示名称。 // // 返回结果: // 显示名称。 protected string DisplayNameValue { get; set; } // 摘要: // Determines whether two System.ComponentModel.DisplayNameAttribute instances // are equal. // // 参数: // obj: // 要进行值的相等性测试的 System.ComponentModel.DisplayNameAttribute。 // // 返回结果: // 如果给定对象的值等于当前对象的值,则为 true;否则为 false。 public override bool Equals(object obj); // // 摘要: // 返回此实例的哈希代码。 // // 返回结果: // 当前 System.ComponentModel.DisplayNameAttribute 的哈希代码。 public override int GetHashCode(); // // 摘要: // 确定此特性是否为默认特性。 // // 返回结果: // 如果此特性是此特性类的默认值,则为 true;否则为 false。 public override bool IsDefaultAttribute(); }}
Model定义如下public class Student{public string Name{get;set;}public int Age {get;set;}}
mvc view 页面
@Model Student@Html.LabelFor(model=>model.Name)@Html.EdditFor(model=>model.Name)
@Html.LabelFor(model=>model.Name) 会render为“姓名”
这种方式显然比直接在view层上hard-code要优化,但是却在Model层上Hardcode了。
一种好的解决方式是使用resource文件,或者将string存储在database中。
然后重写 DisplayNameAttribute
如下
public class LocalizationDisplayName: DisplayNameAttribute {private string ResourceName = string.Empty;public string LocalizationDisplayName(string resourceKey){this.ResourceName = resourceKey;}public override string DisplayName{get {//get localitation string from resource file// or database via resource name.}}}
页:
[1]