用反射实现表单和Model之间互相传自动递数据

当我们进行开发的工作中,有很多的表单,我们要对表单中的每一个信息逐一赋值到Model。表单信息少的话还可以,如果多的话就烦了。在此,我有一个不错的方法可以减轻我们开发中烦恼。

源码地址:https://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);
                }
            }
        }

效果如图:

原文地址:https://www.cnblogs.com/haiconc/p/2346565.html