欢迎光临
我们一直在努力

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

建站超值云服务器,限时71元/月

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

}

}

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » 三层结构ASP.NET程序中,把实体类自动显示在页面上的例子(c#)-.NET教程,Asp.Net开发
分享到: 更多 (0)

相关推荐

  • 暂无文章