/Files/z2002m/DynamicMappingSpike.zip
上面的这个是 从数据库中取数据得到Model. 不过有条件的, 数据库中的字段名称必须与属性名称一致.
从网页控件上取值得到Model , 跟上面的反射代码差不多, 只需要取GetFileldInfo()即可.
再赋值...
代码
public
static
class
HenqPost
<
T
>
where
T:
new
()
{
/**/ /// <summary>
/// 为Model赋值
/// </summary>
/// <typeparam name="T"> Model </typeparam>
/// <param name="t"> model </param>
/// <param name="form"> Request </param>
/// <returns></returns>
public static int GetPost < T > ( ref T t, NameValueCollection form)
{
int va = 0 ;
Type type = t.GetType(); // 获取类型
PropertyInfo[] pi = type.GetProperties(); // 获取属性集合
foreach ( PropertyInfo p in pi )
{
if (form[p.Name] != null )
{
try
{
p.SetValue(t, Convert.ChangeType(form[p.Name], p.PropertyType), null ); // 为属性赋值,并转换键值的类型为该属性的类型
va ++ ; // 记录赋值成功的属性数
}
catch
{
}
}
}
return va;
}
}
{
/**/ /// <summary>
/// 为Model赋值
/// </summary>
/// <typeparam name="T"> Model </typeparam>
/// <param name="t"> model </param>
/// <param name="form"> Request </param>
/// <returns></returns>
public static int GetPost < T > ( ref T t, NameValueCollection form)
{
int va = 0 ;
Type type = t.GetType(); // 获取类型
PropertyInfo[] pi = type.GetProperties(); // 获取属性集合
foreach ( PropertyInfo p in pi )
{
if (form[p.Name] != null )
{
try
{
p.SetValue(t, Convert.ChangeType(form[p.Name], p.PropertyType), null ); // 为属性赋值,并转换键值的类型为该属性的类型
va ++ ; // 记录赋值成功的属性数
}
catch
{
}
}
}
return va;
}
}
在用的时候可以用.
News news
=
new
News();
HenqPost < News > .GetPost( ref news, Request.Form);
HenqPost < News > .GetPost( ref news, Request.Form);