EasyUI入门4 datagrid数据加载的正确方式

概述

为什么说数据加载需要一个正确的方式,因为坑实在是太多了,一般情况下我们至少有这些需求:

  • 页面一打开自动加载数据,不需要还去点一下刷新按钮
  • 数据量大需要分页
  • 为了页面样式对齐需要分页
    当数据超出页面范围时,会弹出滚动条,右侧滚动条会挤出一块空间破坏右边对齐效果(强迫症选项)
  • 有查询条件输入控件,页面刷新时需要采集控件的值
  • 执行完一个操作后,需要执行reload

代码

html文件

<script type="text/javascript">
        $(function () {

            AutoDiscipline();  //绑定专业

            //dg初始化:绑定数据、创建右键菜单
            $("#dg").datagrid({ loadFilter: pagerFilter }).datagrid({
                contentType: "application/x-www-form-urlencoded; charset=UTF-8",
                url: "../../Controller/Interface/POtoPriceLib.ashx?Action=Refresh",
                queryParams: {
                    DisciplineName: encodeURIComponent($('#ddlDiscipline').combobox('getValue')),
                    PurchaseNumber: encodeURIComponent($('#PurchaseNumber').textbox('getValue'))
                },
                onRowContextMenu: function(e, rowIndex, rowData) { //右键时触发事件
                    //三个参数:e里面的内容很多,真心不明白,rowIndex就是当前点击时所在行的索引,rowData当前行的数据
                    e.preventDefault(); //阻止浏览器捕获右键事件
                    $(this).datagrid("clearSelections"); //取消所有选中项
                    $(this).datagrid("selectRow", rowIndex); //根据索引选中该行
                    $('#menu').menu('show', {
                        //显示右键菜单
                        left: e.pageX,//在鼠标点击处显示菜单
                        top: e.pageY
                    });
                    e.preventDefault();  //阻止浏览器自带的右键菜单弹出
                }
            });

            var pager = $('#dg').datagrid('getPager'); // get the pager of datagrid
            pager.pagination({
                pageSize: 20,
                pageNumber: 1,
                pageList: [10, 20, 30, 40, 50],
                beforePageText: '第',//页数文本框前显示的汉字
                afterPageText: '页    共 {pages} 页',
                displayMsg: '当前显示 {from} - {to} 条记录   共 {total} 条记录'
            });

            //选择专业刷新采购包列表.datagrid({ loadFilter: pagerFilter })
            $('#ddlDiscipline').combobox({
                onSelect: function (row) {
                    if (row != null) {
                        $.ajax({
                            contentType: "application/x-www-form-urlencoded; charset=UTF-8",
                            url: "../../Controller/Interface/POtoPriceLib.ashx?Action=Refresh",
                            type: "get",
                            data: {
                                "DisciplineName": encodeURIComponent(row.专业名称),
                                "PurchaseNumber": encodeURIComponent($('#PurchaseNumber').textbox('getValue'))
                            },
                            dataType: "json",
                            success: function (data) {
                                $("#dg").datagrid("options").pageNumber = 1;
                                $("#dg").datagrid("loadData", data);
                            }
                        });

                    }
                }
            });

        });

        //分页用方法
        function pagerFilter(data) {
            if (typeof data.length == 'number' && typeof data.splice == 'function') {   // is array
                data = {
                    total: data.length,
                    rows: data
                }
            }
            var dg = $(this);
            var opts = dg.datagrid('options');
            var pager = dg.datagrid('getPager');
            pager.pagination({
                onSelectPage: function (pageNum, pageSize) {
                    opts.pageNumber = pageNum;
                    opts.pageSize = pageSize;
                    pager.pagination('refresh', {
                        pageNumber: pageNum,
                        pageSize: pageSize
                    });
                    dg.datagrid('loadData', data);
                }
            });
            if (!data.originalRows) {
                data.originalRows = (data.rows);
            }
            var start = (opts.pageNumber - 1) * parseInt(opts.pageSize);
            var end = start + parseInt(opts.pageSize);
            data.rows = (data.originalRows.slice(start, end));
            return data;
        }

        //初始化专业选项
        function AutoDiscipline() {
            $.ajax({
                contentType: "application/x-www-form-urlencoded; charset=UTF-8",
                url: "../../Controller/PurchasePackage/PurchasePackage.ashx?Action=AutoDiscipline",
                type: "get",
                data: {},   //中文须编码,用encodeURIComponent
                dataType: "json",
                success: function (data) {
                    //值显示到input里 - EasyUI写法
                    //var msg = $.parseJSON(data);
                    $("#ddlDiscipline").combobox("loadData", data);  //动态取数据
                    $('#ddlDiscipline').combobox('select', '-全部专业-');
                }
            });

        }

        //刷新合同列表
        function RefreshPOList() {
            $.ajax({
                contentType: "application/x-www-form-urlencoded; charset=UTF-8",
                url: "../../Controller/Interface/POtoPriceLib.ashx?Action=Refresh",
                type: "get",
                data: {
                    "DisciplineName": encodeURIComponent($('#ddlDiscipline').combobox('getValue')),
                    "PurchaseNumber": encodeURIComponent($('#PurchaseNumber').textbox('getValue'))
                },
                dataType: "json",
                success: function (data) {
                    $("#dg").datagrid("options").pageNumber = 1;
                    $("#dg").datagrid("loadData", data);
                }
            });

        }

        //同步到价格库
        function SendToPriceLib() {
            var row = $('#dg').datagrid('getSelected');
            var psguid = row.PSGUID;

            if (row.合同状态代码 == 'A') {
                event.returnValue = confirm("确认要把该合同同步到价格库吗?");
                if (event.returnValue == true) {

                    if (row) {
                        var rsguid = row.RSGUID;
                        $.ajax({
                            contentType: "application/x-www-form-urlencoded; charset=UTF-8",
                            url: "../../Controller/Interface/POtoPriceLib.ashx?Action=SendToPriceLib",
                            type: "post",
                            data: {
                                "PSGUID": psguid
                            },   //中文须编码,用encodeURIComponent
                            dataType: "text",
                            success: function (data) {
                                if (data == "ok") {
                                    $.messager.alert('提示信息', "同步到价格库成功", 'info');
                                    $("#dg").datagrid("reload",
                                        {
                                            "DisciplineName": encodeURIComponent($('#ddlDiscipline').combobox('getValue')),
                                            "PurchaseNumber": encodeURIComponent($('#PurchaseNumber').textbox('getValue'))
                                        });  //动态取数据
                                }
                                else {
                                    $.messager.alert('提示信息', "同步失败," + data, 'warning');
                                }
                            },
                            error: function () {
                                $.messager.alert('提示信息', "同步失败,错误代码20202", 'warning');
                            }
                        });
                    }

                }
                else { }
            }
            else if (row.合同状态代码 == 'R' || row.合同状态代码 == 'G') {
                $.messager.alert('提示信息', "合同未发布不能同步到价格库", 'warning');
            }
            else {
                $.messager.alert('提示信息', "合同状态未知,不能同步到价格库!", 'warning');
            }
        }

    </script>

ashx文件:

       public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            //context.Response.Write("Hello World");

            //获取请求的动作
            string action = context.Request["Action"];
            if (string.IsNullOrEmpty(action)) return;

            //页面参数
            long projectId = Int64.Parse(Encrypt.Base64Decrypt(CookiesHelper.GetCookie_l("MC_pId"))); //项目ID
            string domainName = Encrypt.Base64Decrypt(CookiesHelper.GetCookie_l("MC_doNa"));           //域登录名

            string json_stream = string.Empty;          //dataTable转置成的stream流
            string json_stream_format = string.Empty;   //dataTable转置成的stream流(easyui datagrid格式)

            //支付款项功能需要的页面传值参数
            string psguidInPayment = context.Request["PSGUID"];

            switch (action)
            {
                case "Refresh"://刷新PO列表
                    PriceLib po = new PriceLib();
                    po.ProjectId = projectId;
                    po.Discipline = HttpUtility.UrlDecode(context.Request["DisciplineName"].ToString()); //中文解码
                    po.PONumber = HttpUtility.UrlDecode(context.Request["PurchaseNumber"].ToString()); //中文解码
                    DataTable json_data = po.Select();
                    json_stream = DatatableAndJson.ToJson(json_data);
                    json_stream_format = DatatableAndJson.JsonFormatdg(json_data != null ? json_data.Rows.Count : 0, json_stream);
                    context.Response.Write(json_stream_format);
                    break;
             }
         }

代码说明

AutoDiscipline(); //绑定专业
如果你的页面有下拉框形式的查询条件输入控件,大概会用到这类方法,比如我的页面需要一个下拉框来选择专业,那么在页面初始化的时候这个下拉框里的选项就需要准备好,因此在$(function(){})里面需要一个方法来做这件事。

用queryParams方式传递参数

queryParams: {
     DisciplineName: encodeURIComponent($('#ddlDiscipline').combobox('getValue')),
     PurchaseNumber: encodeURIComponent($('#PurchaseNumber').textbox('getValue'))
},

另一种传递参数的写法:

//dg初始化:绑定数据、创建右键菜单
$("#dg").datagrid({ loadFilter: pagerFilter }).datagrid({
    contentType: "application/x-www-form-urlencoded; charset=UTF-8",
    url: "../../Controller/PurchaseGenerate/PurchaseGenerate.ashx?Action=Refresh&DisciplineName=" + encodeURIComponent($('#ddlDiscipline').combobox('getValue')) + "&PurchaseNumber=" + encodeURIComponent($('#PurchaseNumber').textbox('getValue'))
});

这样写会出现一个奇怪的bug,当你执行完一个动作比如发布合同之后你希望调用reload方法让datagrid刷新,这个刷新将会把你刚才的操作结果,比如合同状态的描述更新到页面上,但是你会发现$(‘#ddlDiscipline’).combobox(‘getValue’)此时取不到正确的值,虽然我选中的选项叫“管道”,凡是返回值始终是“,管道”,字符串的起始位置多出一个逗号,你的reload肯定无法根据多出一个逗号的参数得到正确的数据集,我并没有找到原因但是如果你用queryParams方式传值就没有这个问题了。

带参数使用reload方法

$("#dg").datagrid("reload",
{
  "DisciplineName": encodeURIComponent($('#ddlDiscipline').combobox('getValue')),
  "PurchaseNumber": encodeURIComponent($('#PurchaseNumber').textbox('getValue'))
});  //动态取数据
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xiangcns

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值