下面是一款asp教程.net中实体类对象赋值到表单的实现代码,前几天一个朋友告诉我反射表单赋值到一个实体类的对象方法,下面是一段非常不错的实例。
using system;
using system.data;
using system.configuration;
using system.collections;
using system.collections.generic;
using system.reflection;
using system.collections.specialized;
using system.web.ui;
using system.web.ui.webcontrols;
using system.web.ui.htmlcontrols;
/// <summary>
/// 通过对象设置获取表单值
/// </summary>
namespace com.fun
{
public static class setformtomodel<t>
{
/// <summary>
/// 将表单赋予对对象
/// </summary>
/// <param name="t">实体对象</param>
/// <param name="form">表单集合</param>
public static void getvalue(t t, namevaluecollection form)
{
type type = t.gettype();
propertyinfo[] pi = type.getproperties();
foreach (propertyinfo p in pi)
{
if (form[p.name] != null)
{
p.setvalue(t, convert.changetype(form[p.name], p.propertytype), null);
}
}
}/// <summary>
/// 将对象赋予表单
/// </summary>
/// <param name="t">实体对象</param>
/// <param name="c">页面对象</param>
public static void setvalue(t t,page page)
{
type type = t.gettype();
propertyinfo[] pi = type.getproperties();
foreach (propertyinfo p in pi)
{
system.web.ui.htmlcontrols.htmlinputtext text = page.findcontrol(p.name) as system.web.ui.htmlcontrols.htmlinputtext;
if (text != null)
{
text.value = p.getvalue(t, null).tostring();
}
}}
}
}
//调用
mhousereco mh = new dhousereco().getmodel(id);
com.fun.setformtomodel<mhousereco>.setvalue(mh,this.page);mhousereco mh = new mhousereco();
com.fun.setformtomodel<mhousereco>.getvalue(mh, this.request.form);