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

所属分类: 网络编程 / ASP.NET 阅读数: 1960
收藏 0 赞 0 分享
有一个问题就是 :表单名称和对象的属性名(我是属性赋值 你也可以用字段)要保持一样,,有点不安全,不过后台用挺好的,在说填写表单数据后台用的比较多
复制代码 代码如下:

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);
更多精彩内容其他人还在看

用.NET 2.0压缩/解压功能处理大型数据

用.NET 2.0压缩/解压功能处理大型数据
收藏 0 赞 0 分享

ASP.NET入门随想之检票的老太太

ASP.NET入门随想之检票的老太太
收藏 0 赞 0 分享

ASP与ASP.NET互通COOKIES的一点经验

ASP与ASP.NET互通COOKIES的一点经验
收藏 0 赞 0 分享

ASP.NET2.0数据库入门之SqlDataSource

ASP.NET2.0数据库入门之SqlDataSource
收藏 0 赞 0 分享

ASP.NET2.0数据库入门之SQL Server

ASP.NET2.0数据库入门之SQL Server
收藏 0 赞 0 分享

ASP.NET 2.0下的条件编译

ASP.NET 2.0下的条件编译
收藏 0 赞 0 分享

ASP.NET常用代码

ASP.NET常用代码
收藏 0 赞 0 分享

ASP.NET热点问题解答14个

ASP.NET热点问题解答14个
收藏 0 赞 0 分享

利用ASP.NET技术动态生成HTML页面

利用ASP.NET技术动态生成HTML页面
收藏 0 赞 0 分享

ADO.NET实用技巧两则

ADO.NET实用技巧两则
收藏 0 赞 0 分享
查看更多