第一步创建元数据类
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Reflection; 5 using System.Web; 6 using System.Web.Mvc; 7 8 namespace MvcApplication19 9 {10 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property)]11 public class DisplayTextAttribute : Attribute, IMetadataAware12 {13 private static Type staticResourceType;14 public string DisplayName { get; set; }15 public Type ResourceType { get; set; }16 17 public DisplayTextAttribute()18 {19 this.ResourceType = staticResourceType;20 }21 22 public void OnMetadataCreated(ModelMetadata metadata)23 {24 this.DisplayName = this.DisplayName ?? (metadata.PropertyName ?? metadata.ModelType.Name);25 if (null == this.ResourceType)26 {27 metadata.DisplayName = this.DisplayName;28 return;29 }30 PropertyInfo property = this.ResourceType.GetProperty(this.DisplayName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);31 metadata.DisplayName = property.GetValue(null, null).ToString();32 }33 34 public static void SetResourceType(Type resourceType)35 {36 staticResourceType = resourceType;37 }38 }39 }
第二步创建Person类
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 6 namespace MvcApplication19.Models 7 { 8 public class Person 9 {10 [DisplayText]11 public string Name { get; set; }12 13 [DisplayText]14 public string Sex { get; set; }15 16 [DisplayText]17 public string BirthDay { get; set; }18 [DisplayText]19 public string Dep { get; set; }20 }21 }