三层结构ASP.NET程序中,把实体类自动显示在页面上的例子(c#)
2024-07-10 12:56:43
供稿:网友
 
在这里我们假设这样一个场景:在一个三层bs系统(asp.net)中有一个实体类student,包括name,age两个字段。现在需要把
这个实体类的数据显示在一个studentinfo.aspx页面上,studentinfo.aspx中有两个文本框:studentname(用来显示student.name)
studentage(用来显示student.age).
下面的步骤将通过反射和attribute来实现自动把student实体显示在studentinfo中:
1,首先,先需要实现一个attribute用来表明实体类中的字段与界面中的控件的对应关系。
using system;
using system.reflection
public class controlidattribute:attribute
{ 
 public string id;
 public controlidattribute(string id)
 {
 id=id;
 }
}
2,然后,需要在实体类中给字段绑上controlid
using system;
public class student
{
 [controlid("studentname")]
 public string name;
 [controlid("studentage")]
 public int age;
 public class1(){}
}
3,实现一个工具类来完成实体类显示到界面上的工作
public class pageutility
{
 //遍历页面,绑定数据
 public void binddata( control control,object entity)
 {
 object temp=null;
 foreach(control c in control.controls)
 {
 temp=getvaluefromentity(c.clientid,entity);
 if(c is textbox)
 {
 ((textbox)c).text=temp.tostring();
 }
 if(c.hascontrols())
 {
 binddata(c,entity);
 }
 }
 }
 
 //获取controlidattribute为controlid的值
 private object getvaluefromentity(string controlid,object entity)
 {
 type t = entity.gettype();
 foreach(fieldinfo f in t.getfields())
 {
 foreach(attribute attr in attribute.getcustomattributes(f))
 {
 if(attr is controlidattribute && ((controlidattribute)attr)._id == controlid )
 {
 return f.getvalue(entity);
 }
 }
 }
 return null;
 }
}
菜鸟学堂: