EXT.NET高效开发(二)——封装函数

在上一篇《EXT.NET高效开发(一)——概述》中,大致的介绍了一下EXT.NET。那么本篇就要继续完成未完成的事业了。说到高效开发,那就是八仙过海各显神通。比如使用代码生成器,这点大家可以参考我的这篇帖子《CodeSmith系列(三)——使用CodeSmith生成ASP.NET页面》。本人是比较推崇批量化生产的。当然,本篇的重点不在这,看过标题的人都知道。

在使用EXT.NET的时候(当然不仅仅是EXT.NET),总是要做很多重复的事,于是封装一些实用的函数可以一劳永逸呀。

1)单选框和复选框.

看图说话开始了,如图

image

当选择其他的时候,出框框填写数据。在实际需求中,很多选择项都不是只有A、B、C、D,往往还能自己自定义。遇到这种需求的,每次加个框框跟后面既麻烦又不方便布局,于是秉着不重复造轮子的原则,定义了以下函数:

        /// <summary>
        /// 绑定单选框组(最后一项为可编辑项,保持位置为ID+Hidden)
        /// </summary>
        /// <typeparam name="T">类类型</typeparam>
        /// <param name="lst">泛型集合</param>
        /// <param name="ID">复选框组ID</param>
        /// <param name="TextPropertyName">需要绑定的文本属性字段名(大写小都必须一致)</param>
        /// <param name="ValuePropertyName">需要绑定的值属性字段名(大写小都必须一致)</param>
        /// <param name="CheckedPropertyName">需要绑定的选择属性字段名(大写小都必须一致)</param>
        /// <param name="isCheckedPropertyName">是否是选择属性字段名,如果如false,则CheckedPropertyName表示选中的值</param>
        /// <param name="_ColumnsNumber">显示列数</param>
        /// <param name="_remark">备注项名称,如设置了此项,则可以填写该项备注</param>
        /// <param name="textlen">显示的文本长度</param>
        public static void BindRadioGroup<T>(System.Web.UI.UserControl _userControl, List<T> lst, string ID, string TextPropertyName, string ValuePropertyName, string CheckedPropertyName, bool isCheckedPropertyName, int? _ColumnsNumber, string _remark, int textlen)
        {
            if (lst != null && lst.Count > 0)
            {
                Control _control = _userControl.FindControl(ID);
                if (_control is RadioGroup)
                {
                    //该脚本实现弹框填写其他项,以下是参数
                    //hiddenID:其他项的文本保存位置ID
                    //chk:其他项的CheckBox
                    //orgBoxLabel:原始的BoxLabel
                    string _setRemarkScript =
                    @"
                                function setChkRemark(hiddenID, chk, orgBoxLabel ,textlen) {
                                    if (chk.getValue()) {
                                        Ext.MessageBox.show({
                                            title: orgBoxLabel,
                                            msg: '请输入' + orgBoxLabel + ':',
                                            width: 300,
                                            buttons: Ext.MessageBox.OKCANCEL,
                                            multiline: true,
                                            value: hiddenID.getValue(),
                                            fn: function (btn, text) {
                                                var remark = text.replace(/(^\s*)|(\s*$)/g, '');
                                                if (btn == 'cancel')
                                                    Ext.MessageBox.alert('温馨提示', '操作已取消。');
                                                else if (btn == 'ok') {
                                                    hiddenID.setValue(remark);
                                                    if (remark!='') 
                                                        chk.setBoxLabel(orgBoxLabel+':'+(remark.length>textlen? remark.toString().substring(0,textlen)+'...':remark));
                                                    else
                                                        chk.setBoxLabel(orgBoxLabel);
                                                }
                                            }
                                        });
                                    }
                                }
                    ";
                    //注册函数
                    _userControl.Page.ClientScript.RegisterStartupScript(_userControl.GetType(), "setChkRemark", _setRemarkScript, true);
                    RadioGroup groupRadios = _control as RadioGroup;
                    if (groupRadios == null)
                        return;
                    //groupRadios.SubmitValue = true;
                    #region 【_ColumnsNumber】设置显示列数,为null则一行显示4列。
                    _ColumnsNumber = _ColumnsNumber ?? 4;
                    if (lst.Count <= _ColumnsNumber)
                    {
                        groupRadios.ColumnsNumber = lst.Count;
                    }
                    else
                    {
                        groupRadios.ColumnsNumber = _ColumnsNumber.Value;
                    }
                    #endregion
                    groupRadios.Items.Clear();
                    int i = 0;
                    foreach (var item in lst)
                    {
                        T t = item;
                        Type type = t.GetType();
                        Radio rdo = new Radio();
                        rdo.ID = string.Format("{0}items{1}", ID, i);
                        PropertyInfo TextProInfo = type.GetProperty(TextPropertyName);
                        if (TextProInfo == null)
                            ExtensionMethods.ThrowNullException(type, TextPropertyName);

                        PropertyInfo ValueProInfo = type.GetProperty(ValuePropertyName);
                        if (ValueProInfo == null)
                            ExtensionMethods.ThrowNullException(type, ValuePropertyName);

                        object objText = TextProInfo.GetValue(t, null);
                        rdo.BoxLabel = objText == null ? string.Empty : objText.ToString();
                        object objValue = ValueProInfo.GetValue(t, null).ToString();
                        rdo.Tag = objValue == null ? string.Empty : objValue.ToString();
                        rdo.InputValue = objValue == null ? string.Empty : objValue.ToString();
                        if (!isCheckedPropertyName)
                        {
                            if (rdo.Tag == CheckedPropertyName)
                                rdo.Checked = true;
                            groupRadios.Items.Add(rdo);
                            i++;
                            continue;
                        }
                        PropertyInfo CheckedProInfo = type.GetProperty(CheckedPropertyName);
                        if (CheckedProInfo == null)
                            ExtensionMethods.ThrowNullException(type, CheckedPropertyName);
                        if ((CheckedProInfo.GetValue(t, null) ?? 0).ToString() == "1")
                            rdo.Checked = true;
                        groupRadios.Items.Add(rdo);
                        i++;
                    }
                    groupRadios.Items[groupRadios.Items.Count - 1].Listeners.Check.Handler = "setChkRemark(#{" + ID + "Hidden},this,'" + _remark + "'," + textlen + ");";
                }
                else if (_control is System.Web.UI.WebControls.RadioButtonList)
                {
                    System.Web.UI.WebControls.RadioButtonList _rbl = _control as System.Web.UI.WebControls.RadioButtonList;
                    _rbl.DataTextField = TextPropertyName;
                    _rbl.DataValueField = ValuePropertyName;
                    _rbl.DataSource = lst;
                    _rbl.RepeatDirection = System.Web.UI.WebControls.RepeatDirection.Horizontal;
                    //_rbl.RepeatLayout = RepeatLayout.Flow;
                    _rbl.DataBind();
                    if (!isCheckedPropertyName)
                        _rbl.SelectedValue = CheckedPropertyName;
                }

            }
        }
这样调用起来就方便了,如:
                ExtControlHelper.BindCheckGroup(this, _db.SelectGeneralFromTableINFO(ShopID, CurrentFormID,
                                                                                     "TerminationReason").ToList()
                                                , "cblTerminationReason", "AttributeValue", "AttributeID", "CheckValue",
                                                4, "其他", 8);

不过别忘了在页面上丢一个“<ext:Hidden ID="cblTerminationReasonHidden" runat="server" />”。

为了方便,本人又定义了以下几个函数:

        /// <summary>
        /// 绑定单选框组
        /// </summary>
        /// <typeparam name="T">类类型</typeparam>
        /// <param name="lst">泛型集合</param>
        /// <param name="ID">复选框组ID</param>
        /// <param name="TextPropertyName">需要绑定的文本属性字段名(大写小都必须一致)</param>
        /// <param name="ValuePropertyName">需要绑定的值属性字段名(大写小都必须一致)</param>
        /// <param name="CheckedPropertyName">需要绑定的选择属性字段名(大写小都必须一致)</param>
        /// <param name="isCheckedPropertyName">是否是选择属性字段名,如果如false,则CheckedPropertyName表示选中的值</param>
        /// <param name="_ColumnsNumber">显示列数</param>
        public static void BindRadioGroup<T>(System.Web.UI.UserControl _userControl, List<T> lst, string ID, string TextPropertyName, string ValuePropertyName, string CheckedPropertyName, bool isCheckedPropertyName, int? _ColumnsNumber)
        {
            if (lst != null && lst.Count > 0)
            {
                Control _control = _userControl.FindControl(ID);
                if (_control is RadioGroup)
                {
                    RadioGroup groupRadios = _control as RadioGroup;
                    if (groupRadios == null)
                        return;
                    #region 【_ColumnsNumber】设置显示列数,为null则一行显示4列。
                    _ColumnsNumber = _ColumnsNumber ?? 4;
                    if (lst.Count <= _ColumnsNumber)
                    {
                        groupRadios.ColumnsNumber = lst.Count;
                    }
                    else
                    {
                        groupRadios.ColumnsNumber = _ColumnsNumber.Value;
                    }
                    #endregion
                    groupRadios.Items.Clear();
                    int i = 0;
                    foreach (var item in lst)
                    {
                        T t = item;
                        Type type = t.GetType();
                        Radio rdo = new Radio();
                        rdo.ID = string.Format("{0}items{1}", ID, i);
                        PropertyInfo TextProInfo = type.GetProperty(TextPropertyName);
                        if (TextProInfo == null)
                            ExtensionMethods.ThrowNullException(type, TextPropertyName);

                        PropertyInfo ValueProInfo = type.GetProperty(ValuePropertyName);
                        if (ValueProInfo == null)
                            ExtensionMethods.ThrowNullException(type, ValuePropertyName);

                        object objText = TextProInfo.GetValue(t, null);
                        rdo.BoxLabel = objText == null ? string.Empty : objText.ToString();
                        object objValue = ValueProInfo.GetValue(t, null).ToString();
                        rdo.Tag = objValue == null ? string.Empty : objValue.ToString();
                        rdo.InputValue = objValue == null ? string.Empty : objValue.ToString();

                        if (!isCheckedPropertyName)
                        {
                            if (rdo.Tag == CheckedPropertyName)
                                rdo.Checked = true;
                            groupRadios.Items.Add(rdo);
                            i++;
                            continue;
                        }
                        PropertyInfo CheckedProInfo = type.GetProperty(CheckedPropertyName);
                        if (CheckedProInfo == null)
                            ExtensionMethods.ThrowNullException(type, CheckedPropertyName);


                        if ((CheckedProInfo.GetValue(t, null) ?? 0).ToString() == "1")
                            rdo.Checked = true;
                        groupRadios.Items.Add(rdo);
                        i++;
                    }
                }
                else if (_control is System.Web.UI.WebControls.RadioButtonList)
                {
                    System.Web.UI.WebControls.RadioButtonList _rbl = _control as System.Web.UI.WebControls.RadioButtonList;
                    _rbl.DataTextField = TextPropertyName;
                    _rbl.DataValueField = ValuePropertyName;
                    _rbl.DataSource = lst;
                    _rbl.RepeatDirection = System.Web.UI.WebControls.RepeatDirection.Horizontal;
                    //_rbl.RepeatLayout = RepeatLayout.Flow;
                    _rbl.DataBind();
                    if (!isCheckedPropertyName)
                        _rbl.SelectedValue = CheckedPropertyName;
                }

            }
        }
        /// <summary>
        /// 绑定复选框组
        /// </summary>
        /// <typeparam name="T">类类型</typeparam>
        /// <param name="lst">泛型集合</param>
        /// <param name="ID">复选框组ID</param>
        /// <param name="TextPropertyName">需要绑定的文本属性字段名(大写小都必须一致)</param>
        /// <param name="ValuePropertyName">需要绑定的值属性字段名(大写小都必须一致)</param>
        /// <param name="CheckedPropertyName">需要绑定的选择属性字段名(大写小都必须一致)</param>
        public static void BindCheckGroup<T>(Control _userControl, List<T> lst, string ID, string TextPropertyName, string ValuePropertyName, string CheckedPropertyName, int? _ColumnsNumber)
        {
            if (lst != null && lst.Count > 0)
            {
                Control _control = _userControl.FindControl(ID);
                if (_control is CheckboxGroup)
                {
                    CheckboxGroup groupChks = _control as CheckboxGroup;
                    if (groupChks == null)
                        return;
                    #region 【_ColumnsNumber】设置显示列数,为null则一行显示4列。
                    _ColumnsNumber = _ColumnsNumber ?? 4;
                    if (lst.Count <= _ColumnsNumber)
                    {
                        groupChks.ColumnsNumber = lst.Count;
                    }
                    else
                    {
                        groupChks.ColumnsNumber = _ColumnsNumber.Value;
                    }
                    #endregion
                    groupChks.Items.Clear();
                    int i = 0;
                    foreach (var item in lst)
                    {
                        T t = item;
                        Type type = t.GetType();
                        Checkbox chk = new Checkbox();
                        chk.ID = string.Format("{0}items{1}", ID, i);
                        PropertyInfo TextProInfo = type.GetProperty(TextPropertyName);
                        if (TextProInfo == null)
                            ExtensionMethods.ThrowNullException(type, TextPropertyName);
                        PropertyInfo ValueProInfo = type.GetProperty(ValuePropertyName);
                        if (ValueProInfo == null)
                            ExtensionMethods.ThrowNullException(type, ValuePropertyName);
                        PropertyInfo CheckedProInfo = type.GetProperty(CheckedPropertyName);
                        if (CheckedProInfo == null)
                            ExtensionMethods.ThrowNullException(type, CheckedPropertyName);
                        object objText = TextProInfo.GetValue(t, null);
                        chk.BoxLabel = objText == null ? string.Empty : objText.ToString();
                        object objValue = ValueProInfo.GetValue(t, null).ToString();
                        chk.Tag = objValue == null ? string.Empty : objValue.ToString();
                        chk.InputValue = chk.Tag;
                        //chk.InputValue = objValue == null ? string.Empty : objValue.ToString();
                        var _checkValue = (CheckedProInfo.GetValue(t, null) ?? 0).ToString();
                        if (_checkValue == "1" || (_checkValue != null && _checkValue.ToLower() == "true"))
                            chk.Checked = true;
                        groupChks.Items.Add(chk);
                        i++;
                    }
                }
                else if (_control is System.Web.UI.WebControls.CheckBoxList)
                {
                    System.Web.UI.WebControls.CheckBoxList _cbl = _control as System.Web.UI.WebControls.CheckBoxList;
                    _cbl.RepeatDirection = System.Web.UI.WebControls.RepeatDirection.Horizontal;
                    _cbl.RepeatLayout = System.Web.UI.WebControls.RepeatLayout.Table;
                    _cbl.RepeatColumns = 7;
                    _cbl.Width = System.Web.UI.WebControls.Unit.Parse("100%");
                    foreach (var item in lst)
                    {
                        T t = item;
                        Type type = t.GetType();
                        Checkbox chk = new Checkbox();
                        PropertyInfo TextProInfo = type.GetProperty(TextPropertyName);
                        if (TextProInfo == null)
                            ExtensionMethods.ThrowNullException(type, TextPropertyName);
                        PropertyInfo ValueProInfo = type.GetProperty(ValuePropertyName);
                        if (ValueProInfo == null)
                            ExtensionMethods.ThrowNullException(type, ValuePropertyName);
                        PropertyInfo CheckedProInfo = type.GetProperty(CheckedPropertyName);
                        if (CheckedProInfo == null)
                            ExtensionMethods.ThrowNullException(type, CheckedPropertyName);

                        object objText = TextProInfo.GetValue(t, null);
                        object objValue = ValueProInfo.GetValue(t, null).ToString();

                        System.Web.UI.WebControls.ListItem _li = new System.Web.UI.WebControls.ListItem();
                        _li.Text = objText == null ? string.Empty : objText.ToString();
                        _li.Value = objValue == null ? string.Empty : objValue.ToString();
                        var _checkValue = CheckedProInfo.GetValue(t, null).ToString();
                        if (_checkValue == "1" || (_checkValue != null && _checkValue.ToLower() == "true"))
                            _li.Selected = true;
                        _cbl.Items.Add(_li);
                    }
                }

            }
        }

        /// <summary>
        /// 绑定复选框组(最后一项为可编辑项,保持位置为ID+Hidden)
        /// </summary>
        /// <typeparam name="T">类类型</typeparam>
        /// <param name="lst">泛型集合</param>
        /// <param name="ID">复选框组ID</param>
        /// <param name="TextPropertyName">需要绑定的文本属性字段名(大写小都必须一致)</param>
        /// <param name="ValuePropertyName">需要绑定的值属性字段名(大写小都必须一致)</param>
        /// <param name="CheckedPropertyName">需要绑定的选择属性字段名(大写小都必须一致)</param>
        /// <param name="_ColumnsNumber">显示列数</param>
        /// <param name="_remark">备注项名称,如设置了此项,则可以填写该项备注</param>
        /// <param name="textlen">显示的文本长度</param>
        public static void BindCheckGroup<T>(Control _userControl, List<T> lst, string ID, string TextPropertyName, string ValuePropertyName, string CheckedPropertyName, int? _ColumnsNumber, string _remark, int textlen)
        {
            if (lst != null && lst.Count > 0)
            {
                Control _control = _userControl.FindControl(ID);
                if (_control is CheckboxGroup)
                {
                    ToolTip _tool=new ToolTip();
                    _tool.ID = string.Format("{0}ToolTip", ID);
                    //该脚本实现弹框填写其他项,以下是参数
                    //hiddenID:其他项的文本保存位置ID
                    //chk:其他项的CheckBox
                    //orgBoxLabel:原始的BoxLabel
                    string _setRemarkScript =
                    @"
                                function setChkRemark(hiddenID, chk, orgBoxLabel ,textlen) {
                                    if (chk.getValue()) {
                                        Ext.MessageBox.show({
                                            title: orgBoxLabel,
                                            msg: '请输入' + orgBoxLabel + ':',
                                            width: 300,
                                            buttons: Ext.MessageBox.OKCANCEL,
                                            multiline: true,
                                            value: hiddenID.getValue(),
                                            fn: function (btn, text) {
                                                var remark = text.replace(/(^\s*)|(\s*$)/g, '');
                                                if (btn == 'cancel')
                                                    Ext.MessageBox.alert('温馨提示', '操作已取消。');
                                                else if (btn == 'ok') {
                                                    hiddenID.setValue(remark);
                                                    if (remark!='') 
                                                        chk.setBoxLabel(orgBoxLabel+':'+(remark.length>textlen? remark.toString().substring(0,textlen)+'...':remark));
                                                    else
                                                        chk.setBoxLabel(orgBoxLabel);
                                                }
                                            }
                                        });
                                    }
                                }
                    ";
                    //注册函数
                    _userControl.Page.ClientScript.RegisterStartupScript(_userControl.GetType(), "setChkRemark", _setRemarkScript, true);
                    CheckboxGroup groupChks = _control as CheckboxGroup;
                    if (groupChks == null)
                        return;
                    #region 【_ColumnsNumber】设置显示列数,为null则一行显示4列。
                    _ColumnsNumber = _ColumnsNumber ?? 4;
                    if (lst.Count <= _ColumnsNumber)
                    {
                        groupChks.ColumnsNumber = lst.Count;
                    }
                    else
                    {
                        groupChks.ColumnsNumber = _ColumnsNumber.Value;
                    }
                    #endregion
                    groupChks.Items.Clear();
                    int i = 0;
                    foreach (var item in lst)
                    {
                        T t = item;
                        Type type = t.GetType();
                        Checkbox chk = new Checkbox();
                        chk.ID = string.Format("{0}items{1}", ID, i);
                        PropertyInfo TextProInfo = type.GetProperty(TextPropertyName);
                        if (TextProInfo == null)
                            ExtensionMethods.ThrowNullException(type, TextPropertyName);

                        PropertyInfo ValueProInfo = type.GetProperty(ValuePropertyName);
                        if (ValueProInfo == null)
                            ExtensionMethods.ThrowNullException(type, ValuePropertyName);

                        PropertyInfo CheckedProInfo = type.GetProperty(CheckedPropertyName);
                        if (CheckedProInfo == null)
                            ExtensionMethods.ThrowNullException(type, CheckedPropertyName);

                        object objText = TextProInfo.GetValue(t, null);

                        chk.BoxLabel = objText == null ? string.Empty : objText.ToString();
                        chk.ToolTip = objText == null ? string.Empty : objText.ToString();
                        object objValue = ValueProInfo.GetValue(t, null).ToString();
                        chk.Tag = objValue == null ? string.Empty : objValue.ToString();
                        chk.InputValue = chk.Tag;

                        //chk.InputValue = objValue == null ? string.Empty : objValue.ToString();
                        var _checkValue = (CheckedProInfo.GetValue(t, null) ?? 0).ToString();

                        if (_checkValue == "1" || (_checkValue != null && _checkValue.ToLower() == "true"))
                            chk.Checked = true;
                        //if (i == lst.Count - 1)
                        //{
                        //    chk.Listeners.Check.Handler = "setChkRemark(#{" + ID + "Hidden},this,'" + _remark + "'," + textlen + ");";
                        //    //chk.Icons.Add(Icon.Note);
                        //}
                        groupChks.Items.Add(chk);
                        i++;
                    }
                    groupChks.Items[groupChks.Items.Count - 1].Listeners.Check.Handler = string.Format("setChkRemark(#{{{0}Hidden}},this,'{1}',{2});", ID, _remark, textlen);
                    //groupChks.Items[groupChks.Items.Count - 1].ToolTip=
                }
                else if (_control is System.Web.UI.WebControls.CheckBoxList)
                {
                    System.Web.UI.WebControls.CheckBoxList _cbl = _control as System.Web.UI.WebControls.CheckBoxList;
                    _cbl.RepeatDirection = System.Web.UI.WebControls.RepeatDirection.Horizontal;
                    _cbl.RepeatLayout = System.Web.UI.WebControls.RepeatLayout.Table;
                    _cbl.RepeatColumns = 7;
                    _cbl.Width = System.Web.UI.WebControls.Unit.Parse("100%");
                    foreach (var item in lst)
                    {
                        T t = item;
                        Type type = t.GetType();
                        Checkbox chk = new Checkbox();
                        PropertyInfo TextProInfo = type.GetProperty(TextPropertyName);
                        if (TextProInfo == null)
                            ExtensionMethods.ThrowNullException(type, TextPropertyName);
                        PropertyInfo ValueProInfo = type.GetProperty(ValuePropertyName);
                        if (ValueProInfo == null)
                            ExtensionMethods.ThrowNullException(type, ValuePropertyName);
                        PropertyInfo CheckedProInfo = type.GetProperty(CheckedPropertyName);
                        if (CheckedProInfo == null)
                            ExtensionMethods.ThrowNullException(type, CheckedPropertyName);

                        object objText = TextProInfo.GetValue(t, null);
                        object objValue = ValueProInfo.GetValue(t, null).ToString();

                        System.Web.UI.WebControls.ListItem _li = new System.Web.UI.WebControls.ListItem();
                        _li.Text = objText == null ? string.Empty : objText.ToString();
                        _li.Value = objValue == null ? string.Empty : objValue.ToString();
                        var _checkValue = CheckedProInfo.GetValue(t, null).ToString();
                        if (_checkValue == "1" || (_checkValue != null && _checkValue.ToLower() == "true"))
                            _li.Selected = true;
                        _cbl.Items.Add(_li);
                    }
                }

            }
        }

2)下拉列表。

无图无真相,果断上图。

image

绑定下拉列表,在这里,本人也封装了以下。如下面代码:

        /// <summary>
        /// 通过反射绑定下拉列表
        /// </summary>
        /// <typeparam name="T">类类型</typeparam>
        /// <param name="lst">泛型集合</param>
        /// <param name="ID">下拉列表ID</param>
        /// <param name="TextPropertyName">文本属性名</param>
        /// <param name="ValuePropertyName">值属性名</param>
        /// <param name="_SelectValue">选择的值</param>
        public static void BindComobox<T>(Control _userControl, List<T> lst, string ID, string TextPropertyName, string ValuePropertyName, string _SelectValue)
        {
            if (lst != null && lst.Count > 0)
            {
                ComboBox _cbos = _userControl.FindControl(ID) as ComboBox;
                if (_cbos == null)
                    return;
                _cbos.Items.Clear();
                foreach (var item in lst)
                {
                    T t = item;
                    Type type = t.GetType();
                    ListItem _li = new ListItem();
                    //文本属性
                    PropertyInfo TextProInfo = type.GetProperty(TextPropertyName);
                    if (TextProInfo == null)
                        ExtensionMethods.ThrowNullException(type, TextPropertyName);
                    //值属性
                    PropertyInfo ValueProInfo = type.GetProperty(ValuePropertyName);
                    if (ValueProInfo == null)
                        ExtensionMethods.ThrowNullException(type, ValuePropertyName);

                    object objText = TextProInfo.GetValue(t, null);
                    _li.Text = objText == null ? string.Empty : objText.ToString();
                    object objValue = ValueProInfo.GetValue(t, null).ToString();
                    _li.Value = objValue == null ? string.Empty : objValue.ToString();
                    _cbos.Items.Add(_li);
                }
                if (!string.IsNullOrEmpty(_SelectValue))
                    _cbos.SelectedItem.Value = _SelectValue;
            }
        }

其实还有一种方式可以绑定,但是本人更喜欢这种。比如通过Store:

 _store = new Store { ID = string.Format("_store{0}", Guid.NewGuid().ToString("N")), IDMode = IDMode.Static };
                    _jsonReader = new JsonReader();
                    _jsonReader.Fields.Add(new RecordField("text", RecordFieldType.String));
                    _jsonReader.Fields.Add(new RecordField("value", RecordFieldType.String));
                    _store.Reader.Add(_jsonReader);

然后再加上自己定义的URL和参数,定义几个参数,封装一下,也可以通用,这里我就不继续写下去了。

3)SharePoint中,给EXT.NET赋权。

这段代码,提供给需要的人吧。当初这问题把我折磨得快疯狂了。还好想到了这么一个解决方案。

        /// <summary>
        /// 给EXT.NET脚本赋予特权
        /// </summary>
        /// <param name="ResManager">ResourceManager</param>
        public static void BuildAllPrivilegesForExtNET(this ResourceManager ResManager)
        {
            if (!X.IsAjaxRequest)
            {
                SPSecurity.RunWithElevatedPrivileges(
                    delegate()
                    {
                        ResManager.RenderScripts = ResourceLocationType.Embedded;
                        ResManager.BuildScripts();
                        ResManager.RenderStyles = ResourceLocationType.Embedded;
                        ResManager.BuildStyles();
                    }
                );
            }
        }

4)读取与赋值。

        /// <summary>
        /// 设置类型的属性值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <param name="userControl">用户控件</param>
        public static void SetValues<T>(this System.Web.UI.Control userControl, T t)
        {
            Type type = t.GetType();
            if (type.IsClass)
            {
                var properties = type.GetProperties();
                foreach (var item in properties)
                {
                    if (item.CanWrite)
                    {
                        System.Web.UI.Control control = userControl.FindControl("txt" + item.Name);
                        if (control != null)
                        {
                            string text = string.Empty;
                            if (control is DateField)
                            {
                                DateField _df = control as DateField;

                                if (_df.IsEmpty)
                                {
                                    if (item.PropertyType.IsGenericType && item.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                                        item.SetValue(t, null, null);
                                    //else
                                    //    item.SetValue(t, System.Data.DbType.DateTime., null);
                                    continue;
                                }
                                else
                                    text = _df.Text;
                            }
                            if (control is TextFieldBase)
                                text = (control as TextFieldBase).Text.Trim();

                            if (item.PropertyType.IsEnum)
                            {
                                item.SetValue(t, Enum.ToObject(item.PropertyType, text), null);
                            }
                            else
                            {
                                //判断是否为可为空类型
                                if (item.PropertyType.IsGenericType && item.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                                {
                                    if (item.PropertyType.GetGenericArguments()[0].Equals(typeof(DateTime)) && text == "0001/1/1 0:00:00")
                                        item.SetValue(t, null, null);
                                    else
                                        item.SetValue(t, Convert.ChangeType(text, item.PropertyType.GetGenericArguments()[0]), null);
                                }
                                else
                                    item.SetValue(t, Convert.ChangeType(text, item.PropertyType), null);
                            }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 设置控件的属性值
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="t">类的对象</param>
        /// <param name="userControl">用户控件</param>
        public static void SetControlValues<T>(this System.Web.UI.UserControl userControl, T t)
        {
            Type type = t.GetType();
            if (type.IsClass)
            {
                var properties = type.GetProperties();
                foreach (var item in properties)
                {
                    System.Web.UI.Control control = userControl.FindControl("txt" + item.Name);
                    if (control != null)
                    {
                        if (control is TextFieldBase)
                        {
                            TextFieldBase txt = control as TextFieldBase;
                            object obj = item.GetValue(t, null);
                            if (obj != null)
                                txt.Text = obj.ToString();
                        }
                        else if (control is DisplayField)
                        {
                            DisplayField txt = control as DisplayField;
                            object obj = item.GetValue(t, null);
                            if (obj != null)
                                txt.Text = obj.ToString();
                        }
                    }
                }
            }
        }
上面的代码进行了可为空类型的判断,这点需要注意。
5)设置通用的表单验证脚本。
该出图的时候还是得出图啊。

image

首先需要验证的表单页面得挂上这段JS:
    var valCss = '';

    function showMsg(title, content, cs) {

        if (valCss != cs) {

            valCss = cs;

            Ext.net.Notification.show({

                hideFx: {

                    fxName: 'switchOff',

                    args: [{}]

                },

                showFx: {

                    args: [

                              'C3DAF9',

                              1,

                              {

                                  duration: 2.0

                              }

                          ],

                    fxName: 'frame'

                },

                iconCls: cs,

                closeVisible: true,

                html: content,

                title: title + '   ' + new Date().format('g:i:s A')

            });

        }

    }

然后:

            if (!string.IsNullOrEmpty(_fp.Listeners.ClientValidation.Handler))
                return;
            _fp.Listeners.ClientValidation.Handler =
                @"
                            var isCheckd=valid;var msgs;var msg='';
                            if(typeof(ValCustomValidator)=='function')
                            {
                                msgs=ValCustomValidator(false,valid);
                                if(typeof(msgs.IsVal)!='undefined')
                                {
                                    isCheckd=msgs.IsVal;
                                    if(msgs.Message!='')
                                    msg='<span style=\'color:red;\'>'+msgs.Message+'</span>';
                                }
                                else
                                    isCheckd=msgs;
                            }
                            if(typeof(#{btnSave})!='undefined' && #{btnSave}!=null)#{btnSave}.setDisabled(!isCheckd);
                            if(typeof(#{btnSumbit1})!='undefined' && #{btnSumbit1}!=null)#{btnSumbit1}.setDisabled(!isCheckd);
                         var valCs=isCheckd ? 'valaccept' : 'valexclamation';
                         if (msg=='') msg=isCheckd ? '<span style=\'color:green;\'>验证通过,可以提交数据</span>' : '<span style=\'color:red;\'>输入有误,请检查标红的输入项。</span>';
                         this.getBottomToolbar().setStatus({text :msg, iconCls: valCs});showMsg('温馨提示',msg,valCs);
              ";

顺便解释一下:

  1. 支持在页面上写自定义验证函数“ValCustomValidator”。存在与否都不会引发异常。
  2. 支持页面上防止保存提交按钮,存在与否也没关系。
  3. 你还可以根据自己的情况自定义。

因为这里是通用的,比如默认给每一个表单使用这个验证脚本。那么如何实现自定义验证呢?先欣赏两幅美图:

image

然后右下角就来提示了:

image

这里再贴上具体的JS:

    var ids1 = [
"ctl00_ctl07_g_6fdea0d3_1768_457b_a4ba_ff8b3fc1ea4e_g_6fdea0d3_1768_457b_a4ba_ff8b3fc1ea4e_ASP_wpresources_usercontrols_form_packagenotice_ascx_txt100E44D593C054BFD9B13EBFBD9AAA41A", "ctl00_ctl07_g_6fdea0d3_1768_457b_a4ba_ff8b3fc1ea4e_g_6fdea0d3_1768_457b_a4ba_ff8b3fc1ea4e_ASP_wpresources_usercontrols_form_packagenotice_ascx_txt124C85DB03BA04EBDBE5055EAC5FACAEC", "ctl00_ctl07_g_6fdea0d3_1768_457b_a4ba_ff8b3fc1ea4e_g_6fdea0d3_1768_457b_a4ba_ff8b3fc1ea4e_ASP_wpresources_usercontrols_form_packagenotice_ascx_txt1DF8DD73F58F84492B89D7194D52D947F", "ctl00_ctl07_g_6fdea0d3_1768_457b_a4ba_ff8b3fc1ea4e_g_6fdea0d3_1768_457b_a4ba_ff8b3fc1ea4e_ASP_wpresources_usercontrols_form_packagenotice_ascx_txt1ADD45D7F275148769BD0E20013DC25F2"];

    var ids2 = ["ctl00_ctl07_g_6fdea0d3_1768_457b_a4ba_ff8b3fc1ea4e_g_6fdea0d3_1768_457b_a4ba_ff8b3fc1ea4e_ASP_wpresources_usercontrols_form_packagenotice_ascx_txt200E44D593C054BFD9B13EBFBD9AAA41A", "ctl00_ctl07_g_6fdea0d3_1768_457b_a4ba_ff8b3fc1ea4e_g_6fdea0d3_1768_457b_a4ba_ff8b3fc1ea4e_ASP_wpresources_usercontrols_form_packagenotice_ascx_txt224C85DB03BA04EBDBE5055EAC5FACAEC", "ctl00_ctl07_g_6fdea0d3_1768_457b_a4ba_ff8b3fc1ea4e_g_6fdea0d3_1768_457b_a4ba_ff8b3fc1ea4e_ASP_wpresources_usercontrols_form_packagenotice_ascx_txt2DF8DD73F58F84492B89D7194D52D947F", "ctl00_ctl07_g_6fdea0d3_1768_457b_a4ba_ff8b3fc1ea4e_g_6fdea0d3_1768_457b_a4ba_ff8b3fc1ea4e_ASP_wpresources_usercontrols_form_packagenotice_ascx_txt2ADD45D7F275148769BD0E20013DC25F2"];
    function valSumMax(ids, maxValue, msg) {
        if (ids != null && ids.length > 0) {
            var _temp = 0;
            for (var i = 0; i < ids.length; i++) {
                var value = Ext.getCmp(ids[i]).getValue();
                var _currentValue = parseInt(value);
                _temp += isNaN(_currentValue) ? 0 : _currentValue;
                if (_temp > maxValue) {

                    var message = { 'IsVal': false, 'Message': msg != "" ? msg : ("当前值" + _temp + "超过最大值" + maxValue + "。") };
                    return message;
                }
            }
        }
        var message = { 'IsVal': true, 'Message': '' };
        return message;
    }
    function CustomValidator() {
        var msg = valSumMax(ids1, 2, "美容顾问服装最多只能填2件。请修改总数。");
        if (!msg.IsVal)
            return msg;
        msg = valSumMax(ids2, 6, "美容师服装最多只能填6件。请修改总数。");
        return msg;
    }
    function ValCustomValidator(isVal, valid) {
        if (typeof (valid) != 'undefined' && (!valid))
            return valid;
        if (typeof (isVal) == 'undefined' || isVal == null || isVal) {
            var msg = CustomValidator();
            if (!msg.IsVal) {
                Ext.MessageBox.show({
                    title: '错误',
                    msg: msg.Message,
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.ERROR
                });
                return false;
            } else {
                return true;
            }
        } else {
            return CustomValidator();
        }
    }

看到上面那一串ID没,这就是不使用IDMode的后果。因为刚开始接触,未发现有这么个好东东。

好了,今天就到此为止吧,我们还会见面的。我上面用了一些反射,大家都说反射性能怎么样怎么样,但是这点消耗有时大可不必担心,不过有些还是可以优化的,比如绑定下拉列表,使用Store结合HttpProxy的话,就完全不需要用反射了。只是每次绑定的时候,代码里面要调用下,然后Httphandler类也要写点代码。

当然我封装的并不止这一些,但是只适合我自己的系统,就不方便拿出来了。

兄弟我先抛块砖,有玉的赶紧砸过来吧。

posted @ 2011-07-26 18:05  雪雁  阅读(6154)  评论(11编辑  收藏  举报