Example of a three-layer structure ASP.net program that automatically displays entity classes on the page (C #)

Source: Internet
Author: User
Tags foreach reflection
Asp.net| Program | show | page Here we assume a scenario where there is an entity class student in a three-tier BS system (asp.net), including name,age two fields. Now need to put
The data for this entity class is displayed on a studentinfo.aspx page with two text boxes in studentinfo.aspx: Studentname (used to show Student.name)
Studentage (used to display student.age).
The following steps will automatically display the student entity in the Studentinfo by reflection and attribute:
1, first, you need to implement an attribute that indicates the corresponding relationship between the field in the entity class and the controls in the interface.
Using System;
Using System.Reflection
public class Controlidattribute:attribute
{
public string ID;

Public Controlidattribute (String id)
{
Id=id;
}
}
2, and then you need to bind the field to the ControlID in the entity class
Using System;
public class Student
{
[ControlID ("Studentname")]
public string name;
[ControlID ("Studentage")]
public int age;

Public Class1 () {}
}
3, implement a tool class to complete the work of the entity class display to the interface
public class Pageutility
{
Traversing pages, binding data
public void Binddata (Control control,object entity)
{
Object Temp=null;
foreach (Control C-control. Controls)
{
Temp=getvaluefromentity (c.clientid,entity);

if (c is TextBox)
{
((TextBox) c). Text=temp. ToString ();
}
if (C.hascontrols ())
{
Binddata (c,entity);
}
}
}

Gets the value of the Controlidattribute as 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;
}
}





Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.