三层结构ASP.NET程序中,把实体类自动显示在页面上的例子(c#)

王朝c#·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

在这里我们假设这样一个场景:在一个三层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;

}

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航