使用反射将业务对象绑定到 ASP.NET 窗体控件(修改篇)

本文介绍了一种在ASP.NET中实现窗体控件与实体类属性自动双向绑定的方法,通过设置控件ID与实体属性名相同,简化了数据绑定过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

MSDN上面的代码和下载的代码包也有那么多问题,晕死。
综合下载的代码和MSDN上的说明,修改了这段代码,现在能正常使用,特别是很多字段放在窗体上的时候,使用起来非常方便。

具体用法:把窗体上的控件ID属性与实体层的属性设置成一致。
绑定实体层到窗体的时候用:
web.model .test  Test = new web.model.test();
Test = bll.GetModel(id);
BindObjectToControls(model,this);

要把窗体数据绑定到实体层的时候用:
BindControlsToObject(model,this);

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Reflection;

namespace WEB
{
    /// <summary>
    /// A class with two static methods <see cref="BindObjectToControls"/> and <see cref="BindControlsToObject"/>
    /// used to bind the values of and object's properties with web <see cref="Control"/>s that have their
    /// ID property set to the name of the object property.
    /// </summary>
    public class FormBinding
    {
        /// <summary>
        /// Binds an object's properties to <see cref="Control"/>s with the same ID as the propery name.
        /// </summary>
        /// <param name="obj">The object whose properties are being bound to forms Controls</param>
        /// <param name="container">The control in which the form Controls reside (usually a Page or ContainerControl)</param>
        public static void BindObjectToControls(object obj, Control container)
        {
            if (obj == null) return;

            // Get the properties of the business object
            //
            Type objType = obj.GetType();
            PropertyInfo[] objPropertiesArray = objType.GetProperties();

            foreach (PropertyInfo objProperty in objPropertiesArray)
            {

                Control control = container.FindControl(objProperty.Name);
                if (control == null) continue;

                // handle ListControls (DropDownList, CheckBoxList, RadioButtonList)
                //
                if (control is ListControl)
                {
                    ListControl listControl = (ListControl)control;
                    string propertyValue = objProperty.GetValue(obj, null).ToString();
                    ListItem listItem = listControl.Items.FindByValue(propertyValue);
                    if (listItem != null) listItem.Selected = true;

                }
                else
                {
                    // get the properties of the control
                    //
                    Type controlType = control.GetType();
                    PropertyInfo[] controlPropertiesArray = controlType.GetProperties();

                    // test for common properties
                    //
                    bool success = false;
                    success = FindAndSetControlProperty(obj, objProperty, control, controlPropertiesArray, "Checked", typeof(bool));

                    if (!success)
                        success = FindAndSetControlProperty(obj, objProperty, control, controlPropertiesArray, "SelectedDate", typeof(DateTime));

                    if (!success)
                        success = FindAndSetControlProperty(obj, objProperty, control, controlPropertiesArray, "Value", typeof(String));

                    if (!success)
                        success = FindAndSetControlProperty(obj, objProperty, control, controlPropertiesArray, "Text", typeof(String));

                }
            }
        }

        /// <summary>
        /// Looks for a property name and type on a control and attempts to set it to the value in an object's property
        /// of the same name.
        /// </summary>
        /// <param name="obj">The object whose properties are being retrieved</param>
        /// <param name="objProperty">The property of the object being retrieved</param>
        /// <param name="control">The control whose ID matches the object's property name.</param>
        /// <param name="controlPropertiesArray">An array of the control's properties</param>
        /// <param name="propertyName">The name of the Control property being set</param>
        /// <param name="type">The correct type for the Control property</param>
        /// <returns>Boolean for whether the property was found and set</returns>
        private static bool FindAndSetControlProperty(object obj, PropertyInfo objProperty, Control control, PropertyInfo[] controlPropertiesArray, string propertyName, Type type)
        {
            // iterate through control properties
            //
            foreach (PropertyInfo controlProperty in controlPropertiesArray)
            {
                // check for matching name and type
                //
                if (controlProperty.Name == propertyName && controlProperty.PropertyType == type)
                {
                    // set the control's property to the business object property value
                    //
                    controlProperty.SetValue(control, Convert.ChangeType(objProperty.GetValue(obj, null), type), null);
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// Binds your the values in <see cref="Control"/>s to a business object.
        /// </summary>
        /// <param name="obj">The object whose properties are being bound to Control values</param>
        /// <param name="container">The control in which the form Controls reside (usually a Page or ContainerControl)</param>
        public static void BindControlsToObject(object obj, Control container)
        {
            if (obj == null) return;

            // Get the properties of the business object
            //   
            Type objType = obj.GetType();
            PropertyInfo[] objPropertiesArray = objType.GetProperties();

            foreach (PropertyInfo objProperty in objPropertiesArray)
            {

                Control control = container.FindControl(objProperty.Name);
                if (control == null) continue;
                if (control is ListControl)
                {
                    ListControl listControl = (ListControl)control;
                    if (listControl.SelectedItem != null)
                        objProperty.SetValue(obj, Convert.ChangeType(listControl.SelectedItem.Value, objProperty.PropertyType), null);

                }
                else
                {
                    // get the properties of the control
                    //
                    Type controlType = control.GetType();
                    PropertyInfo[] controlPropertiesArray = controlType.GetProperties();

                    // test for common properties
                    //
                    bool success = false;
                    success = FindAndGetControlProperty(obj, objProperty, control, controlPropertiesArray, "Checked", typeof(bool));

                    if (!success)
                        success = FindAndGetControlProperty(obj, objProperty, control, controlPropertiesArray, "SelectedDate", typeof(DateTime));

                    if (!success)
                        success = FindAndGetControlProperty(obj, objProperty, control, controlPropertiesArray, "Value", typeof(String));

                    if (!success)
                        success = FindAndGetControlProperty(obj, objProperty, control, controlPropertiesArray, "Text", typeof(String));
                }
            }
        }

        private static bool FindAndGetControlProperty(object obj,PropertyInfo objProperty, Control control, PropertyInfo[] controlPropertiesArray, string propertyName, Type type)
        {
            // 在整个控件属性中进行迭代
            foreach (PropertyInfo controlProperty in controlPropertiesArray)
            {
                // 检查匹配的名称和类型
                if (controlProperty.Name == "Text" && controlProperty.PropertyType == typeof(String))
                {
                    // 将控件的属性设置为
                    // 业务对象属性值
                    try
                    {
                        objProperty.SetValue(obj, Convert.ChangeType(controlProperty.GetValue(control, null), objProperty.PropertyType), null);
                        return true;
                    }
                    catch
                    {
                        // 无法将来自窗体控件
                        // 的数据转换为
                        // objProperty.PropertyType
                        return false;
                    }
                }
            }
            return true;
        }

    }
}
 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值