当前位置:Gxlcms > asp.net > asp.net中实体类对象赋值到表单的实现代码

asp.net中实体类对象赋值到表单的实现代码

时间:2021-07-01 10:21:17 帮助过:33人阅读

有一个问题就是 :表单名称和对象的属性名(我是属性赋值 你也可以用字段)要保持一样,,有点不安全,不过后台用挺好的,在说填写表单数据后台用的比较多
代码如下:
  1. <br>using System; <br>using System.Data; <br>using System.Configuration; <br>using System.Collections; <br>using System.Collections.Generic; <br>using System.Reflection; <br>using System.Collections.Specialized; <br>using System.Web.UI; <br>using System.Web.UI.WebControls; <br>using System.Web.UI.HtmlControls; <br>/// <summary> <br>/// 通过对象设置获取表单值 <br>/// </summary> <br>namespace Com.Fun <br>{ <br>public static class SetFormToModel<T> <br>{ <br>/// <summary> <br>/// 将表单赋予对对象 <br>/// </summary> <br>/// <param name="t">实体对象</param> <br>/// <param name="form">表单集合</param> <br>public static void GetValue(T t, NameValueCollection form) <br>{ <br>Type type = t.GetType(); <br>PropertyInfo[] pi = type.GetProperties(); <br>foreach (PropertyInfo p in pi) <br>{ <br>if (form[p.Name] != null) <br>{ <br>p.SetValue(t, Convert.ChangeType(form[p.Name], p.PropertyType), null); <br>} <br>} <br>} <br><br>/// <summary> <br>/// 将对象赋予表单 <br>/// </summary> <br>/// <param name="t">实体对象</param> <br>/// <param name="c">页面对象</param> <br>public static void SetValue(T t,Page page) <br>{ <br>Type type = t.GetType(); <br>PropertyInfo[] pi = type.GetProperties(); <br>foreach (PropertyInfo p in pi) <br>{ <br>System.Web.UI.HtmlControls.HtmlInputText text = page.FindControl(p.Name) as System.Web.UI.HtmlControls.HtmlInputText; <br>if (text != null) <br>{ <br>text.Value = p.GetValue(t, null).ToString(); <br>} <br>} <br><br>} <br>} <br>} <br><br><br>//调用 <br>MHouseReco mh = new DHouseReco().GetModel(id); <br>Com.Fun.SetFormToModel<MHouseReco>.SetValue(mh,this.Page); <br><br>MHouseReco mh = new MHouseReco(); <br>Com.Fun.SetFormToModel<MHouseReco>.GetValue(mh, this.Request.Form); <br>

人气教程排行