新客网WWW.XKER.COM:致力做中国最专业的网络学院!
学院: 操作系统 - 网络应用 - 服务器 - 网络安全 - 工具软件 - 办公软件 - Web开发 - 数据库 - 网页设计 - 图形图像 - 媒体动画 - 硬件学堂 - 存储频道 - QQ专区
您的位置:首页 > 软件开发 > .Net开发 > Asp.net教程 > 正文:三层结构ASP.NET程序中,把实体类自动显示在页面上的例子(c#)

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

新客网 XKER.COM 2004-12-06 来源: 收藏本文
在这里我们假设这样一个场景:在一个三层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;
}
}



收藏】 【评论】 【推荐】 【投稿】 【打印】 【关闭
发表评论
要记得去论坛讨论,点击注册新会员匿名评论
评论内容:不能超过250字,需审核后才会公布,请自觉遵守互联网相关政策法规。
阅读排行
随机推荐
实用信息推荐