.NET开发

本类阅读TOP10

·NHibernate快速指南(翻译)
·vs.net 2005中文版下载地址收藏
·【小技巧】一个判断session是否过期的小技巧
·VB/ASP 调用 SQL Server 的存储过程
·?dos下编译.net程序找不到csc.exe文件
·通过Web Services上传和下载文件
·学习笔记(补)《.NET框架程序设计(修订版)》--目录
·VB.NET实现DirectDraw9 (2) 动画
·VB.NET实现DirectDraw9 (1) 托管的DDraw
·建站框架规范书之——文件命名

分类导航
VC语言Delphi
VB语言ASP
PerlJava
Script数据库
其他语言游戏开发
文件格式网站制作
软件工程.NET开发
三层结构ASP.NET程序中,把实体类自动显示在页面上的例子(c#)

作者:未知 来源:月光软件站 加入时间:2005-2-28 月光软件站

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




相关文章

相关软件