首页 > 代码库 > 页面批量赋值

页面批量赋值

在ASP.net中,遇到数据库字段较多,给前端赋值的情况好麻烦的说

 1 //通过Id获取前端控件,必须是ruanatServer的控件 2     public Control GetControl(string name) 3     { 4         object obj; 5         try 6         { 7             var a = this.GetType(); 8             obj = this.GetType().GetField(name, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.IgnoreCase).GetValue(this); 9         }10         catch11         {12             return null;13         }14 15         return ((Control)obj);16     }17 18     //遍历Model给前端赋值19     public void SetControlsValue<T>(T obj) where T:new()20     {21         Type t = obj.GetType();22 23         foreach (var item in t.GetProperties())24         {25             Control ctrl = GetControl(item.Name);26             if (ctrl != null)27             {28                 if (ctrl.GetType().Name == "TextBox")29                 {30                     TextBox a = (TextBox)ctrl;31                     if (a != null)32                     {33                         try34                         {35                             a.Text = item.GetValue(obj, null).ToString();36                         }37                         catch38                         {39                             a.Text = "";40                         }41                     }42                 }43                 if (ctrl.GetType().Name == "DropDownList")44                 {45                     DropDownList a = (DropDownList)ctrl;46                     if (a != null)47                     {48                         try49                         {50                             a.SelectedValue = http://www.mamicode.com/item.GetValue(obj, null).ToString();51                         }52                         catch53                         {54                             a.SelectedValue = http://www.mamicode.com/"请选择";55                         }56                     }57                 }58 59                 if (ctrl.GetType().Name == "Label")60                 {61                     Label a = (Label)ctrl;62                     if (a != null)63                     {64                         try65                         {66                             a.Text = item.GetValue(obj, null).ToString();67                         }68                         catch69                         {70                             a.Text = "";71                         }72                     }73                 }74             }75         }76     }

只是有一个要求,前端的Id必须与后台类的属性一致

页面批量赋值