一、基于控件ID/实体属性名映射的数据绑定
我的这个组件暂时命名为DataBinder好了注意和System.Web.UI.DataBinder区分),我们用它来将一个实体对象绑定给指定的容器控件中的所有子控件。下面是DataBinder的定义,两个BindData方法实现具体的绑定操作。
- public class DataBinder
- public event EventHandler<DataBindingEventArgs> DataItemBinding;
- public event EventHandler<DataBindingEventArgs> DataItemBound;
- public static IEnumerable<BindingMapping> BuildBindingMappings(Type entityType, Control container, string suffix = "");
- public void BindData(object entity, Control container, string suffix = "");
- public void BindData( object entity,IEnumerable<BindingMapping> bindingMappings);
- }
本文开头所说,自动批量的数据绑定依赖于控件和作为数据源实体类型的映射关系。在这里,我直接采用控件ID和实体属性名之间的映射。也就是说,在对于界面上控件进行命名的时候,应该根据对应的实体类型属性名进行规范命名。
另一方面,作为数据源的对象来说,它的所有属性并不都是为数据绑定而涉及。为了让DataBinder能够自动筛选用于绑定的属性,我在相应的属性上应用了一个自定义特性:DataPropertyAttribute。比如,下面的Customer对象会在后续的演示中用到,它的每一个数据属性都应用了这样一个DataPropertyAttribute特性。
- public class Customer
- {
- [DataProperty]
- public string ID { get; set; }
- [DataProperty]
- public string FirstName { get; set; }
- [DataProperty]
- public string LastName { get; set; }
- [DataProperty]
- public string Gender { get; set; }
- [DataProperty]
- public int? Age { get; set; }
- [DataProperty]
- public DateTime? BirthDay { get; set; }
- [DataProperty]
- public bool? IsVip { get; set; }
- }
本站文章为和通数据库网友分享或者投稿,欢迎任何形式的转载,但请务必注明出处.
同时文章内容如有侵犯了您的权益,请联系QQ:970679559,我们会在尽快处理。