In the three-tier structure ASP.NET program, the entity class is automatically displayed on the page (C #)

xiaoxiao2021-03-06  39

Here we assume such a scene: there is a physical class Student in a three-layer BS system (ASP.NET), including two fields of Name, AGE. Now you need to display the data of this entity class on a StudentInfo.aspx page, there are two text boxes in StudentInfo.aspx: StudentName (to display student.name) Studentage (used to display student.age). The following steps Automatically display the STUDENT entity in StudentInfo by reflection and attribute: 1. First, first need to implement an attribute to indicate the correspondence between the fields in the entity class and the controls in the interface. Using system; using system.reflectionPublic Class ControlidAttribute: Attribute {public string ID;

public ControlIDAttribute (string id) {ID = id;}} 2, then, need to tie field in ControlIDusing System entity class; public class Student {[ControlID ( "StudentName")] public string name; [ControlID ( "StudentAge ")] Public int Age;

Public class1 () {}} 3, implement a tool class to complete the physical class to display the work of the work public class pageutility {// Traverse page, binding data public void binddata (control control, object entity) {Object Temp = null "For the 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);}}} // Get the value of ControlidAttribute for 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;}}

转载请注明原文地址:https://www.9cbs.com/read-85761.html

New Post(0)