欢迎投稿

今日深度:

一句代码实现批量数据绑定 上(1)(2)

一、基于控件ID/实体属性名映射的数据绑定

我的这个组件暂时命名为DataBinder好了注意和System.Web.UI.DataBinder区分),我们用它来将一个实体对象绑定给指定的容器控件中的所有子控件。下面是DataBinder的定义,两个BindData方法实现具体的绑定操作。

  1. public class DataBinder     
  2.      
  3.     public event EventHandler<DataBindingEventArgs> DataItemBinding;     
  4.     public event EventHandler<DataBindingEventArgs> DataItemBound;     
  5.       
  6.     public static IEnumerable<BindingMapping> BuildBindingMappings(Type entityType, Control container, string suffix = "");             
  7.     public void BindData(object entity, Control container, string suffix = "");     
  8.     public void BindData( object entity,IEnumerable<BindingMapping> bindingMappings);    

本文开头所说,自动批量的数据绑定依赖于控件和作为数据源实体类型的映射关系。在这里,我直接采用控件ID和实体属性名之间的映射。也就是说,在对于界面上控件进行命名的时候,应该根据对应的实体类型属性名进行规范命名。

另一方面,作为数据源的对象来说,它的所有属性并不都是为数据绑定而涉及。为了让DataBinder能够自动筛选用于绑定的属性,我在相应的属性上应用了一个自定义特性:DataPropertyAttribute。比如,下面的Customer对象会在后续的演示中用到,它的每一个数据属性都应用了这样一个DataPropertyAttribute特性。

  1. public class Customer     
  2. {     
  3.     [DataProperty]     
  4.     public string ID { get; set; }     
  5.     [DataProperty]     
  6.     public string FirstName { get; set; }     
  7.     [DataProperty]     
  8.     public string LastName { get; set; }     
  9.     [DataProperty]    
  10.     public string Gender { get; set; }    
  11.     [DataProperty]    
  12.     public int? Age { get; set; }    
  13.     [DataProperty]    
  14.     public DateTime? BirthDay { get; set; }    
  15.     [DataProperty]    
  16.     public bool? IsVip { get; set; }    


www.htsjk.Com true http://www.htsjk.com/shujukujc/18893.html NewsArticle 一、基于控件ID/实体属性名映射的数据绑定 我的这个组件暂时命名为DataBinder好了注意和System.Web.UI.DataBinder区分),我们用它来将一个实体对象绑定给指定...
评论暂时关闭