asp.net中實體類對象賦值到表單的實現代碼

來源:互聯網
上載者:User

有一個問題就是 :表單名稱和對象的屬性名稱(我是屬性賦值 你也可以用欄位)要保持一樣,,有點不安全,不過後台用挺好的,在說填寫表單資料後台用的比較多 複製代碼 代碼如下: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);

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.