看到这个随笔:利用反射,泛型,静态方法快速获取表单值到Model。
我整理了一下
我整理了一下
Code
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Reflection;
using System.Collections.Specialized;
public class ModelHeper
{
/// <summary>
/// 请确定控件命名规则
/// </summary>
/// <typeparam name="T">model的类型</typeparam>
/// <param name="model">model实体</param>
/// <param name="e">当前页Request.Form表单</param>
/// <returns>成功赋值的个数</returns>
public static T modelBind<T>(NameValueCollection fromTest) where T : new()
{
T model = new T();
object NewValue = new object(); //暂时存储一些值
int i = 0;
PropertyInfo[] pifs = typeof(T).GetProperties(); //获取model 所有的属性
foreach (var p in pifs)
{
string ControlNameStr = "txt" + p.Name.ToString();
if (fromTest[ControlNameStr] != null) //检查对应的控件是否为空
{
try
{
NewValue = Convert.ChangeType(fromTest[ControlNameStr], p.PropertyType);//将控件值转化对应属性的值
p.SetValue(model, NewValue, null); //设置 属性值
i++;
}
catch (Exception)
{
}
}
}
return model;
}
}
----------------------------测试这个类using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Reflection;
using System.Collections.Specialized;
public class ModelHeper
{
/// <summary>
/// 请确定控件命名规则
/// </summary>
/// <typeparam name="T">model的类型</typeparam>
/// <param name="model">model实体</param>
/// <param name="e">当前页Request.Form表单</param>
/// <returns>成功赋值的个数</returns>
public static T modelBind<T>(NameValueCollection fromTest) where T : new()
{
T model = new T();
object NewValue = new object(); //暂时存储一些值
int i = 0;
PropertyInfo[] pifs = typeof(T).GetProperties(); //获取model 所有的属性
foreach (var p in pifs)
{
string ControlNameStr = "txt" + p.Name.ToString();
if (fromTest[ControlNameStr] != null) //检查对应的控件是否为空
{
try
{
NewValue = Convert.ChangeType(fromTest[ControlNameStr], p.PropertyType);//将控件值转化对应属性的值
p.SetValue(model, NewValue, null); //设置 属性值
i++;
}
catch (Exception)
{
}
}
}
return model;
}
}
Code
InvitationInfo invitioninfo = ModelHeper.modelBind<InvitationInfo>(Request.Form); //InvitationInfo 类 与页面上的值自动绑定
//打印model 的属性
Type it = typeof(InvitationInfo);
PropertyInfo[] ps = it.GetProperties();
object o = new object();
foreach (var p in ps)
{
Response.Write(p.Name + " 值为:" + p.GetValue(invitioninfo, null) + "</br>");
}
InvitationInfo invitioninfo = ModelHeper.modelBind<InvitationInfo>(Request.Form); //InvitationInfo 类 与页面上的值自动绑定
//打印model 的属性
Type it = typeof(InvitationInfo);
PropertyInfo[] ps = it.GetProperties();
object o = new object();
foreach (var p in ps)
{
Response.Write(p.Name + " 值为:" + p.GetValue(invitioninfo, null) + "</br>");
}