三層結(jié)構(gòu)ASP.NET程序中,把實(shí)體類自動(dòng)顯示在頁(yè)面上的例子(c#)
2024-07-10 12:56:43
供稿:網(wǎng)友
在這里我們假設(shè)這樣一個(gè)場(chǎng)景:在一個(gè)三層bs系統(tǒng)(asp.net)中有一個(gè)實(shí)體類student,包括name,age兩個(gè)字段。現(xiàn)在需要把
這個(gè)實(shí)體類的數(shù)據(jù)顯示在一個(gè)studentinfo.aspx頁(yè)面上,studentinfo.aspx中有兩個(gè)文本框:studentname(用來(lái)顯示student.name)
studentage(用來(lái)顯示student.age).
下面的步驟將通過(guò)反射和attribute來(lái)實(shí)現(xiàn)自動(dòng)把student實(shí)體顯示在studentinfo中:
1,首先,先需要實(shí)現(xiàn)一個(gè)attribute用來(lái)表明實(shí)體類中的字段與界面中的控件的對(duì)應(yīng)關(guān)系。
using system;
using system.reflection
public class controlidattribute:attribute
{
public string id;
public controlidattribute(string id)
{
id=id;
}
}
2,然后,需要在實(shí)體類中給字段綁上controlid
using system;
public class student
{
[controlid("studentname")]
public string name;
[controlid("studentage")]
public int age;
public class1(){}
}
3,實(shí)現(xiàn)一個(gè)工具類來(lái)完成實(shí)體類顯示到界面上的工作
public class pageutility
{
//遍歷頁(yè)面,綁定數(shù)據(jù)
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;
}
}
菜鳥學(xué)堂: