您的位置: 首页 > 技术文档 > 网络编程 > 数据对象类表单自动绑定
回到列表 珊瑚虫IP库浅析
用户名:
密 码: 忘记密码
注册会员 游览论坛 论坛帮助
 数据对象类表单自动绑定

作者:martin0728 时间: 2006-12-27 文档类型:翻译 来自:蓝色理想
浏览统计 total:1195 | year:342 | Quarter:342 | Month:342 | Week:342 | today:6

DarkangleFormBinder

本文附带的代码在Asp.Net 2.0下面调试通过

先讲一下背景

在.Net多层结构程序中,我们会使用一些O/R MAPPING的工具将数据库表或视图映射成实体数据模形用于封装数据,开发中我们可能经常会写这样的代码,例如,我们有一个Student的表,包含一些字段,如Name, Sex, Age, Grade, Height, Weight, ChooseClass.....

我们假设有一个录入学生信息的表单,我们可能会写这样的一些代码,在前台上:

姓名:<asp:TextBox ID="Name" runat="Server" />
年龄:<asp:TextBox ID="Age" runat = "Server" />
年级:<aspropDownList ID="Grade" runat = "server" />
课外活动: <asp:CheckBoxList ID="ChooseClass" runat= "server" />

后台呢:

我们需要先构造一个新的对象:

Student s= new Student();

然后设置它的属性:

s.Name = Name.Text;
s.Age = Age.Text;
s.Grade = Grade.SelectedValue;

然后保存到后台数据库

如果是读取一条记录出来显示在页面上,我们可能先要取得一个对象实例:

Student s = bll.GetStudentById(id);
Name.Text = s.Name;
Age.Text = s.Age;
Grade.Items.FindByValue(s.Grade).Selected = true;

上面标红的部分代码可能会非常多,尤其是在字段比较多的时候,设定这些值就非常麻烦,不但不能漏掉,还要做类型转换等,稍有不小心就会出错.

现在我们可以利用反射的方法将这些属性自动与控件值关联起来,这样就不用手动地编写这些代码了.

具体内容请看我的示例工程文件.注意要在Web.Config中加上控件的引用路径.

这些代码参考了MSDN上面的内容,但是原来的代码有BUG,并且不支持可以多项选择的控件.我在这里加入了两个控件,分别是DarkangleCheckBoxList和DarkangleListBox 这两个控件支持将多项选择的属性以逗号分开的方式存储于数据库字段中.  比如,学生.课余活动 = "照象,游泳,足球",不需要写额外的代码即可直接绑定到多项选择控件.

目前支持的绑定控件有:Label,TextBox,CheckBox,DarkangleCheckBoxList,DarkangleListBox(如果您只需要单项选择,则可以使用自带的ListBox控件),ListBox,DropDownList, RadioButton,RadioButtonList,日历控件.

希望我写的东西对您的开发有所帮助.

Good luck~~~~;)

源代码与示例打包下载

应版主大人要求,把源码贴出来的,其实我提供的下载包里面是有源码的,就在类工程里面,随便也把原来那个老外的也帖上来,我修改了部分内容,原来那个代码运行起来也是有问题的。

先帖我的:

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

namespace Darkangle
{
    public class FormBinder
    {
        public static void BindObjectToControls(object obj, Control container)
        {
            if (obj == null) return;
            Type objType = obj.GetType();
            PropertyInfo[] objPropertiesArray = objType.GetProperties();
            foreach (PropertyInfo objProperty in objPropertiesArray)
            {
                Control control = container.FindControl(objProperty.Name);
                bool success = false;
                bool isCustom = false;
                if (control is DarkangleListBox)
                {
                    DarkangleListBox listBox = (DarkangleListBox)control;
                    string propertyValue = objProperty.GetValue(obj, null).ToString();
                    listBox.SetListValue(propertyValue);
                    isCustom = true;
                }
                if (control is DarkangleCheckBoxList)
                {
                    DarkangleCheckBoxList checkBoxList = (DarkangleCheckBoxList)control;
                    string propertyValue = objProperty.GetValue(obj, null).ToString();
                    checkBoxList.SetListValue(propertyValue);
                    isCustom = true;
                }
                if (!isCustom)
                {
                    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
                    {
                        Type controlType = control.GetType();
                        PropertyInfo[] controlPropertiesArray = controlType.GetProperties();
                        success = FindAndSetControlProperty(obj, objProperty, control, controlPropertiesArray, "Checked", typeof(bool));
                        if (!success)
                        {
                            success = FindAndSetControlProperty(obj, objProperty, control, controlPropertiesArray, "SelectedDate", typeof(DateTime));
                            if (success)
                                FindAndSetControlProperty(obj, objProperty, control, controlPropertiesArray, "VisibleDate", typeof(DateTime));
                        }
                        if (!success)
                            success = FindAndSetControlProperty(obj, objProperty, control, controlPropertiesArray, "Value", typeof(String));
                        if (!success)
                            success = FindAndSetControlProperty(obj, objProperty, control, controlPropertiesArray, "Text", typeof(String));
                    }
                }
            }
        }
        private static bool FindAndSetControlProperty(object obj, PropertyInfo objProperty, Control control, PropertyInfo[] controlPropertiesArray, string propertyName, Type type)
        {
            foreach (PropertyInfo controlProperty in controlPropertiesArray)
            {
                if (controlProperty.Name == propertyName && controlProperty.PropertyType == type)
                {
                    controlProperty.SetValue(control, Convert.ChangeType(objProperty.GetValue(obj, null), type), null);
                    return true;
                }
            }
            return false;
        }
        public static void BindControlsToObject(object obj, Control container)
        {
            if (obj == null) return;
            Type objType = obj.GetType();
            PropertyInfo[] objPropertiesArray = objType.GetProperties();
            foreach (PropertyInfo objProperty in objPropertiesArray)
            {
                bool success = false;
                bool isCustom = false;
                Control control = container.FindControl(objProperty.Name);
                if (control is DarkangleListBox)
                {
                    DarkangleListBox listBox = (DarkangleListBox)control;
                    if (listBox.SelectedIndex > -1)
                        objProperty.SetValue(obj, Convert.ChangeType(listBox.GetListValue(), objProperty.PropertyType), null);
                    isCustom = true;
                }
                if (control is DarkangleCheckBoxList)
                {
                    DarkangleCheckBoxList checkBoxList = (DarkangleCheckBoxList)control;
                    if (checkBoxList.SelectedIndex > -1)
                        objProperty.SetValue(obj, Convert.ChangeType(checkBoxList.GetListValue(), objProperty.PropertyType), null);
                    isCustom = true;
                }
                if (!isCustom)
                {
                    if (control is ListControl)
                    {
                        ListControl listControl = (ListControl)control;
                        if (listControl.SelectedItem != null)
                            objProperty.SetValue(obj, Convert.ChangeType(listControl.SelectedItem.Value, objProperty.PropertyType), null);
                    }
                    else
                    {
                        Type controlType = control.GetType();
                        PropertyInfo[] controlPropertiesArray = controlType.GetProperties();

                        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 == propertyName && controlProperty.PropertyType == type)
                {
                    try
                    {
                        objProperty.SetValue(obj, Convert.ChangeType(controlProperty.GetValue(control, null), objProperty.PropertyType), null);
                        return true;
                    }
                    catch
                    {
                        return false;
                    }
                }
            }
            return false;
        }
    }
}

这两个是我护展出来的控件:

using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;

namespace System.Web.UI.WebControls
{
   
    public class DarkangleCheckBoxList : CheckBoxList
    {
        public void SetListValue(string listValue)
        {
            if (listValue == null || listValue.Trim() == string.Empty)
                return;
            string[] valueList = listValue.Split(new char[] { ',' });
            if (valueList.Length == 0)
                return;
            for (int i = 0; i < valueList.Length; i++)
            {
                if (valueList[i].Length != 0 && valueList[i] != string.Empty)
                    this.Items.FindByValue(valueList[i]).Selected = true;
            }
        }
        public string GetListValue()
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < this.Items.Count; i++)
            {
                if (this.Items[i].Selected)
                    sb.Append(this.Items[i].Value + ",");
            }
            return sb.Remove(sb.Length - 1, 1).ToString();
        }
    }
    public class DarkangleListBox : ListBox
    {
        public void SetListValue(string listValue)
        {
            if (listValue == null || listValue.Trim() == string.Empty)
                return;
            string[] valueList = listValue.Split(new char[] { ',' });
            if (valueList.Length == 0)
                return;
            for (int i = 0; i < valueList.Length; i++)
            {
                if (valueList[i].Length != 0 && valueList[i] != string.Empty)
                    this.Items.FindByValue(valueList[i]).Selected = true;
            }
        }
        public string GetListValue()
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < this.Items.Count; i++)
            {
                if (this.Items[i].Selected)
                    sb.Append(this.Items[i].Value + ",");
            }
            return sb.Remove(sb.Length-1,1).ToString();
        }
    }
}

经典论坛讨论
http://bbs.blueidea.com/thread-2707666-1-1.html

出处:蓝色理想
责任编辑:blue

◎进入论坛网络编程版块参加讨论

相关文章 更多相关链接
数据引起的思考
简洁的表单验证程序
常见可用性错误——表单组件错误
用css制作表单并体验亲和力
SPL3.0数据连接详解
热门搜索:CSS Fireworks 设计比赛 网页制作 Dreamweaver Studio8 Flash
站点最新 站点最新列表
熊猫烧香图标病毒
寻找07年中国50位优秀网页设计师
上海老弄堂里的邻家少女Melody
光线也疯狂
用Photoshop做脸部美容
登封政府门户网站新版发布
Fireworks抠图之枝繁叶茂的树木
Google 百度 搜索引擎习惯的分析
网页制作前台之javascript
《Flash网站建设技术精粹》
栏目最新 栏目最新列表
用Photoshop做脸部美容
Fireworks抠图之枝繁叶茂的树木
Google 百度 搜索引擎习惯的分析
网页制作前台之javascript
苹果图标制作——组合的技巧
数据对象类表单自动绑定
苹果图标制作——立体化图标
苹果图标制作——形状的建立
Flash AS2 中的拍照图片无损压缩
用Photoshop打造ipod nano

蓝色理想版权申明:除部分特别声明不要转载,或者授权我站独家播发的文章外,大家可以自由转载我站点的原创文章,但原作者和来自我站的链接必须保留(非我站原创的,按照原来自一节,自行链接)。文章版权归我站和作者共有。

转载要求:转载之图片、文件,链接请不要盗链到本站,且不准打上各自站点的水印,亦不能抹去我站点水印。

特别注意:本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

本文现有 1 条评论 评分:- llllllllllllllllllll + 评分人数: 1 ,平均分: 1.00


Aether Publish at 2006-12-28 14:04:48 评分1
确实有不少的文章解释了类似的办法,
但是,反射会消耗比常规超出30甚至100被的资源,也是被实验证实过的。
对新手可以用于理解反射的用法,
但是不适合实战。
您的评论
用户名:  口令:
说明:输入正确的用户名和密码才能参与评论。如果您不是本站会员,你可以注册 为本站会员。
注意:文章中的链接、内容等需要修改的错误,请用报告错误,以利文档及时修改。
不评分 1 2 3 4 5
注意:请不要在评论中含与内容无关的广告链接,违者封ID
请您注意:
·不良评论请用报告管理员,以利管理员及时删除。
·尊重网上道德,遵守中华人民共和国的各项有关法律法规
·承担一切因您的行为而直接或间接导致的民事或刑事法律责任
·本站评论管理人员有权保留或删除其管辖评论中的任意内容
·您在本站发表的作品,本站有权在网站内转载或引用
·参与本评论即表明您已经阅读并接受上述条款
推荐文档 | 打印文档 | 评论文档 | 报告错误  
专业书推荐 更多内容
Don't Make Me Think 第2版
《Flash第一步系列》
《交互设计之路》
《Dreamweaver 从基础到实践》
《色彩管理》
《情感化设计》
《GUI设计禁忌》