用反射實現表單和Model之間互相傳自動遞數據


當我們進行開發的工作中,有很多的表單,我們要對表單中的每一個信息逐一賦值到Model。表單信息少的話還可以,如果多的話就煩了。在此,我有一個不錯的方法可以減輕我們開發中煩惱。

源碼地址:http://files.cnblogs.com/haiconc/FormModelWeb.zip

 

現在有一個Model:

namespace FormModelWeb
{
    public class Member
    {
        public int Height { get; set; }

        public int Weight{ get; set; }

        public string Name { get; set; }

        public DateTime Birthday { get; set; }
    }
}
它的屬性有int,string,DateTime類型。

 Member model = new Member()
                {
                    Name = "Tom",
                    Height = 160,
                    Weight = 50,
                    Birthday = DateTime.Parse("2000-05-02")
                };

現在生成一個Model的實例

前台頁面表單如下

    姓名:<asp:TextBox ID="t_Name" runat="server"></asp:TextBox><br />
    身高:<asp:TextBox ID="t_Height" runat="server"></asp:TextBox>cm<br />
    體重:<asp:TextBox ID="t_Weight" runat="server"></asp:TextBox>kg<br />
    生日:<asp:TextBox ID="t_Birthday" runat="server"></asp:TextBox><br />

注意,每個控件的ID都和Model的某個屬性后面相同,前綴都是“t_”。

我們把Model的值傳遞給頁面時

用這個語句:

FormModel.SetForm<Member>(this, model, "t_");

“t_"是ID的前綴。

SetForm的方法源碼如下

 /// <summary>
        /// 設置表單數據
        /// </summary>
        public static void SetForm<T>(Page Ucontrol, T enity, string prefix)
        {
            foreach (PropertyInfo p in typeof(T).GetProperties())
            {
                Control ctrl = FindControl(Ucontrol, prefix + p.Name);
                if (ctrl != null)
                {
                    string value = string.Empty;
                    if (p.GetValue(enity, null) != null)
                        value = p.GetValue(enity, null).ToString().Trim();
                    else
                        continue;

                    WebControlValue.SetValue(ctrl, value);
                }
            }
        }

WebControlValue.SetValue方法源碼太多,就請打開附件源碼查看

運行之后表單自動就會初始化好內容了

把表單信息傳遞給Model

    Member model2 = new Member();
            FormModel.GetForm<Member>(this, model2, "t_");
            Literal1.Text = string.Format("信息為:姓名{0},身高{1}cm,體重{2}kg,生日{3}",model2.Name,model2.Height,model2.Weight,model2.Birthday);

FormModel.GetForm方法源碼如下:

/// <summary>
        /// 取得表單數據
        /// </summary>
        public static void GetForm<T>(Page Ucontrol, T entity, string prefix)
        {
            foreach (PropertyInfo p in typeof(T).GetProperties())
            {
                Control ctrl = FindControl(Ucontrol, prefix + p.Name);

                if (ctrl != null)
                {
                    object value = WebControlValue.GetValue(ctrl);
                    SetPropertyValue<T>(p, value.ToString(), entity);
                }
            }
        }

效果如圖:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM