JQueryEasyUI信息管理实例

简介: 1、前端页面代码  信息列表 var grid; function getwidth() { return document.
1、前端页面代码
 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="News.aspx.cs" Inherits="SysManager_NewsManager_News" %>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>信息列表</title>
    <link href="../Css/default.css" rel="stylesheet" type="text/css" />
    <link rel="stylesheet" type="text/css" href="../../Share/JQueryEasyUI/themes/default/easyui.css" />
    <link rel="stylesheet" type="text/css" href="../../Share/JQueryEasyUI/themes/icon.css" />
    <script type="text/javascript" src="../../Share/Scripts/jquery-1.4.1.min.js"></script>
    <script type="text/javascript" src="../../Share/JQueryEasyUI/jquery.easyui.min.1.2.2.js"></script>
    <script type="text/javascript">
        var grid;
        function getwidth() {

            return document.body.clientWidth * 0.99;
        }

        function resizeGrid() {
            $('#test').datagrid('resize', {
                width: getwidth()

            });

            $('#p').panel('resize', {
                width: getwidth()


            });


        }

        function edit(bh)  //转到编辑页面   
        {
            var page = $("#HF_PAGESIZE").val();
            window.location.href = 'NewsEdit.aspx?newsId=' + bh + '&p=' + page;
        }

        function qdel(index) {  //删除操作
            alert(index);
            $.messager.confirm('确认', '确认删除?', function (row) {
                if (row) {
                    var selectedRow = $('#test').datagrid('getSelected');  //获取选中行   
                    //                    $.ajax({  
                    //                        url:'delHandler.ashx?id='+selectedRow.xsbh+'&type=stu',    
                    //                        success:function(){alert('删除成功');}  
                    //                    });
                    $('#test').datagrid('deleteRow', index);
                }
            })
        }



        $(function () {

            Bind();



        });

 

        function Bind() {

            var pag = $("#HF_PAGESIZE").val();
           
            var url = "../../Share/Controller/NewsTool.ashx?action=list&p=" + pag;
            //alert(url);
            grid = $('#test').datagrid({
                title: '数据显示窗口',
                iconCls: 'icon-reload',
                loadMsg: '数据装载中......',
                //width: function(){return document.body.clientWidth*0.9},
                //height: 350,
                nowrap: true,
                striped: true,
                url: url,
                sortName: 'SortIndex',
                sortOrder: 'desc',
                remoteSort: true,
                idField: 'SortIndex',
                pageSize: 20, //每页显示的记录条数,默认为10  
                pageList: [10, 15, 20, 25, 30, 35, 40], //可以设置每页记录条数的列表 
                frozenColumns: [[
                    { field: 'ck', checkbox: true, height: 200 }
                //                , { title: 'id', field: 'id', width: 80, sortable: true }
                ]],
                columns: [[
                    { field: 'Title', title: '标题', width: 320 },
                    { field: 'CatId', title: '类别', width: 120,
                        formatter: function (value, rec, index) {
                            var s = getCatName(value);
                            return s;
                        }
                    },
                    { field: 'SortIndex', title: '排序', width: 120 },
                    { field: 'UserName', title: '发布人', width: 120 },
                    { field: 'CreateDate', title: '时间', width: 120 },

                    { field: 'opt', title: '操作', width: 200, align: 'center',
                        formatter: function (value, rec, index) {

                            var e = '<a href="#" mce_href="#" onclick="edit(' + rec.id + ')">编辑</a> ';
                           //var d = '<a href="#" mce_href="#" onclick="qdel(' + index + ')">删除</a> ';
                           var d="";
                            return  e + d;
                        }
                    }


                ]],
                pagination: true, // 是否显示分页   
                rownumbers: true, // 是否显示行号   
                fitColumns: true,
                singleSelect: false,
                toolbar: [{
                    text: '新增',
                    iconCls: 'icon-add',
                    handler: add
                }, '-', {
                    text: '删除',
                    iconCls: 'icon-remove',
                    handler: del
                }

                ]

            });

            //加底部文字
            $('#test').datagrid('getPager').pagination({
                beforePageText: '第', //页数文本框前显示的汉字 
                afterPageText: '页    共 {pages} 页',
                displayMsg: '当前显示{from}到{to}  共{total}记录',
                pageNumber:<%=pageIndex %>,
                onBeforeRefresh: function (pageNumber, pageSize) {
                    $(this).pagination('loading');
                    //alert('pageNumber:' + pageNumber + ',pageSize:' + pageSize);
                    $("#HF_PAGESIZE").attr("value", pageNumber);
                    $(this).pagination('loaded');
                },
                onSelectPage: function (pageNumber, pageSize) {
                 
                    $("#HF_PAGESIZE").attr("value", pageNumber);
                  
                }
            });

      

        }

        function SearchBind() {

            var DTypeList = document.getElementById('DTypeList');
            var Ctype = DTypeList.options[DTypeList.selectedIndex].value;
            var Title = $('#txtTitle').val();
            var url = "../../Share/Controller/NewsTool.ashx?action=list&m=" + Math.random();
            if (Ctype != "") {
                url += "&Ctype=" + Ctype;
            }
            if (Title != "") {
                url += "&Title=" + Title;
            }

            //grid.datagrid('reload');
            grid.datagrid('loadData', { total: 0, rows: [] });//先清空数据避免缓存
            grid.datagrid({ url: url });
           
           
        }
       

        function add() {

            window.location.href = 'NewsAdd.aspx';  
        }


        function getSelectedArr() {
            var ids = [];

            var rows = $('#test').datagrid('getSelections');
            for (var i = 0; i < rows.length; i++) {
                ids.push(rows[i].id);
            }
            return ids;
        }
        function getSelectedID() 
        {
            var ids = getSelectedArr();
            return ids.join(',');
        }
        function arr2str(arr) 
        {

            return arr.join(',');
        }
        function del()
         {
            var arr = getSelectedArr();
            if (arr.length > 0) 
            {
             $.messager.confirm('提示信息', '您确认要删除吗?', function (data)
              {
                 if (data) 
                 {
               
                     $.ajax({
                         url: '/Share/Controller/NewsTool.ashx?action=del&id=' + arr2str(arr),
                         type: 'GET',
                         timeout:0,
                         async: false,
                         error: function () {
                             $.messager.alert('错误', '删除失败!', 'error');
                         },
                         success: function (data) 
                         {
                         
                             eval('data=' + data);
                             if (data.success) {

                                 grid.datagrid('reload');
                                 //grid.datagrid('clearSelections');
                             } else {
              
                                 $.messager.alert('错误', data.msg, 'error');
                             }
                         }
                     });
                 }
             });

            } else {
                Msgshow('请先选择要删除的记录。');
            }
        }

        function Msgshow(msg) {

            $.messager.show({
                title: '提示',
                msg: msg,
                showType: 'show'
            });
        }


        function getCatName(CatId) {

            var html = $.ajax({
                type: "POST",
                url: "/Share/Controller/NewsTool.ashx",
                data: { HttpType: "GetCName", CatId: CatId },
                async: false
            }).responseText;

  
            return html;
        }

    </script>
    <style type="text/css">
        .datagrid-view tr
        {
            height: 22px !important;
            line-height: 22px !important;
        }
    </style>
</head>
<body onresize="resizeGrid();">
    <form id="form1" runat="server">
    <asp:HiddenField ID="HF_PAGESIZE" runat="server" Value="1" />
    <div id="p" class="easyui-panel" title="信息搜索" dosize="true" style="height: 100px;
        padding: 10px; background: #fafafa; margin-bottom: 5px;" iconcls="icon-search"
        collapsible="true" loadingmessage="信息搜索...">
        <table>
            <tr>
                <td>
                    信息分类:
                </td>
                <td>
                    <asp:DropDownList ID="DTypeList" class="easyui-validatebox" runat="server" AppendDataBoundItems="true">
                        <asp:ListItem Value="0">请选择</asp:ListItem>
                    </asp:DropDownList>
                </td>
                <td>
                    信息标题:
                </td>
                <td>
                    <input class="easyui-validatebox" id="txtTitle">
                </td>
                <td>
                    <a id="btnEp" class="easyui-linkbutton" icon="icon-ok" href="javascript:void(0)"
                        onclick="SearchBind();">搜索</a>
                </td>
            </tr>
        </table>
    </div>
    <table id="test">
    </table>
    </form>
</body>
</html>


OrederTool.ashx2、OrederTool.ashx执行代码

<%@ WebHandler Language="C#" Class="OrederTool" %>


using System;
using System.Web;
using System.Text;
using System.Data;
using Sq.Common;
using System.Collections.Generic;
public class OrederTool : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "json/application;";
        //context.Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);
        //context.Response.AddHeader("pragma", "no-cache"); 
        //context.Response.AddHeader("cache-control", ""); 
        //context.Response.CacheControl = "no-cache"; 
        //context.Response.Charset = Encoding.UTF8.ToString();
        string sReturnJson = string.Empty;
        string sqlexe = string.Empty;
        string action = ParamsofEasyUI.RequstString("action");
        switch (action)
        {
            case "save":
                sReturnJson = save();
                break;
            case "del":
                sReturnJson = delete();
                break;
            case "list":
            case "query":
                sReturnJson = getData(action);
                break;
            case "get":
                sReturnJson ="";
                break;
            default:
                break;
        }


        if (action == "Zreo")
        {
            string OrderID = context.Request.Form["OrderID"].ToString();
            string ProCode = context.Request.Form["ProCode"].ToString();
            string type = context.Request.Form["type"].ToString();

            sReturnJson = UpZreo(OrderID, ProCode, type).ToString();

        }
        if (action == "PayState")
        {
            string OrderID = context.Request.Form["OrderID"].ToString();
            sReturnJson = PayState(OrderID).ToString();
        }

        if (action == "Unlock")
        {
            string OrderID = context.Request.Form["OrderID"].ToString();
            sReturnJson = Unlock(OrderID).ToString();
        }
        context.Response.Write(sReturnJson);
    }

    public string Unlock(string OrderID)
    {

        Model.A_OrderInfo OrderInfoModel = new BLL.A_OrderInfo().GetModel(Convert.ToInt32(OrderID));
        if (OrderInfoModel != null)
        {
            OrderInfoModel.IsLock = 0;
            bool bg = new BLL.A_OrderInfo().Update(OrderInfoModel);
            if (bg)
            {
                return JsonUtil.Serialize(new { Lock = 1 });
            }
            else
            {

                return JsonUtil.Serialize(new { Lock = 0 });

            }
        }
        else
        {
            return JsonUtil.Serialize(new { Lock = 0 });
        }

    }
    
    
    public string PayState(string OrderID)
    {

        Model.A_OrderInfo OrderInfoModel = new BLL.A_OrderInfo().GetModel(Convert.ToInt32(OrderID));
        if (OrderInfoModel != null)
        {

            return JsonUtil.Serialize(new { PayState = OrderInfoModel.PayState });
        }
        else
        {
            return JsonUtil.Serialize(new { PayState = 0 });
        }

    }
    private string UpZreo(string OrderID, string ProCode, string type)
    {
        List<Model.A_OrderPro> list = new BLL.A_OrderPro().GetList(null, "OrderId=" + OrderID + " and ProCode='" + ProCode + "'", null);
        if (list.Count > 0)
        {
            if (type == "true")
            {
                list[0].IsZero = 1;
                bool fg = new BLL.A_OrderPro().Update(list[0]);
                Model.A_OrderInfo OrderInfoModel = new BLL.A_OrderInfo().GetModel(Util.GetInt(OrderID));
                if (OrderInfoModel != null)
                {
                    if (OrderInfoModel.WarningMsg.Trim() != "")
                    {
                        OrderInfoModel.WarningMsg = OrderInfoModel.WarningMsg + " 订单缺货";
                    }
                    else
                    {
                        OrderInfoModel.WarningMsg = " 订单缺货";
                    }

                    new BLL.A_OrderInfo().Update(OrderInfoModel);
                }
                if (fg)
                {
                    return JsonUtil.Serialize(new { code = 1, content = "<font color='red'>" + OrderInfoModel.WarningMsg.Trim() + "<font>" });
                }
            }
            else
            {
                list[0].IsZero = 0;
                bool fg = new BLL.A_OrderPro().Update(list[0]);
                if (fg)
                {
                    List<Model.A_OrderPro> ll = new BLL.A_OrderPro().GetList(null, "OrderId=" + OrderID + " and IsZero=1", null);
                    if (ll.Count < 1)
                    {
                        Model.A_OrderInfo OrderInfoModel = new BLL.A_OrderInfo().GetModel(Util.GetInt(OrderID));
                        if (OrderInfoModel != null)
                        {
                            if (OrderInfoModel.WarningMsg.Trim() != "")
                            {
                                OrderInfoModel.WarningMsg = OrderInfoModel.WarningMsg.Replace("订单缺货", "");
                                if (OrderInfoModel.WarningMsg.Trim() == "")
                                {
                                    OrderInfoModel.WarningMsg = "正常订单";
                                }
                            }
                            new BLL.A_OrderInfo().Update(OrderInfoModel);
                            return JsonUtil.Serialize(new { code = 1, content = "<font color='red'>" + OrderInfoModel.WarningMsg.Trim() + "<font>" });
                        }
                    }
                    else
                    {
                        return JsonUtil.Serialize(new { code = 1, content = "<font color='red'>订单缺货<font>" });
                    }
                }

            }
        }

        return JsonUtil.Serialize(new { code = 0, content = "正常订单" });
    }
    
    private string getData(string action)
    {
        string order = ParamsofEasyUI.order;
        string sort = ParamsofEasyUI.sort;
        int page = ParamsofEasyUI.page;

        int rows = ParamsofEasyUI.rows;


        string sWhere = string.Empty;
        string sqlexe = string.Empty;
        if (action.Equals("list"))
        {
            DataTable dt = null;
            string Consignee = ParamsofEasyUI.RequstString("Consignee");
            if (Consignee != "")
            {
                string sql = String.Format("SELECT *,(SELECT OrderStateName FROM A_OrderState where id=A_OrderInfo.OrderState) AS OrderStateName FROM A_OrderInfo where Consignee='{0}' order by {1} {2}", Consignee, sort, order);
                dt = new SQLServerDAL.A_OrderInfo().GetDataSet(sql).Tables[0];
            }
            else
            {
                string sql = String.Format("SELECT *,(SELECT OrderStateName FROM A_OrderState where id=A_OrderInfo.OrderState) AS OrderStateName FROM A_OrderInfo order by {0} {1}", sort, order);
                dt = new SQLServerDAL.A_OrderInfo().GetDataSet(sql).Tables[0];

            }
            string josn = Json4EasyUI.onDataGrid(dt, page, rows);
            return josn;
        }

        return null;
    }


   
    
    private string delete()
    {
        string sReturnJson = string.Empty;
        string id = ParamsofEasyUI.RequstString("id");

        return sReturnJson;
    }

    private string save()
    {
        string sReturnJson = string.Empty;

        return sReturnJson;
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}

3、Json4EasyUI帮助类

using System;
using System.Collections.Generic;
using System.Web;
using System.Text;
using System.Data;
using Sq.Common;

/// <summary>
///Json4EasyUI 的摘要说明
/// </summary>
public class Json4EasyUI
{
    public Json4EasyUI()
    {
        //
        //TODO: 在此处添加构造函数逻辑
        //
    }
    public static string onDataGrid1(DataTable dt, int start, int end)
    {
        StringBuilder jsonBuilder = new StringBuilder();
        jsonBuilder.Append("{\"total\":" + dt.Rows.Count + ",\"rows\":[");
        for (int i = start; i < end; i++)
        {
            jsonBuilder.Append("{");
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                jsonBuilder.Append("\"");
                jsonBuilder.Append(dt.Columns[j].ColumnName);
                jsonBuilder.Append("\":\"");
                jsonBuilder.Append(dt.Rows[i][j].ToString());
                jsonBuilder.Append("\",");
            }
            jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
            jsonBuilder.Append("},");
        }
        jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
        jsonBuilder.Append("]}");
        return jsonBuilder.ToString();
    }

    /// <summary>
    /// 填充DataGrid的Json数据格式
    /// </summary>
    /// <param name="dt">数据集</param>
    /// <param name="page">页数</param>
    /// <param name="rows">每页行数</param>
    /// <returns></returns>
    public static string onDataGrid(DataTable dt, int page, int rows, int Counts)
    {
        page = (page == 0) ? 1 : page;
        rows = (rows == 0) ? 10 : rows;
        int start = (page - 1) * rows;
        int end = page * rows;
        end = (end > Counts) ? Counts : end;
        StringBuilder jsonBuilder = new StringBuilder();
        jsonBuilder.Append("{\"total\":" + Counts + ",\"rows\":[");
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            jsonBuilder.Append("{");
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                Type type = dt.Columns[j].DataType;
                jsonBuilder.Append("\"");
                jsonBuilder.Append(dt.Columns[j].ColumnName);
                jsonBuilder.Append("\":\"");
                jsonBuilder.Append(GetToJson.StringFormat(dt.Rows[i][j].ToString(), type));
                jsonBuilder.Append("\",");
            }
            jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
            jsonBuilder.Append("},");
        }
        jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
        jsonBuilder.Append("]}");
        return jsonBuilder.ToString();
    }



    /// <summary>
    /// 填充DataGrid的Json数据格式
    /// </summary>
    /// <param name="dt">数据集</param>
    /// <param name="page">页数</param>
    /// <param name="rows">每页行数</param>
    /// <returns></returns>
    public static string onDataGrid(DataTable dt, int page, int rows)
    {
        page = (page == 0) ? 1 : page;
        rows = (rows == 0) ? 10 : rows;
        int start = (page - 1) * rows;
        int end = page * rows;
        end = (end > dt.Rows.Count) ? dt.Rows.Count : end;
        StringBuilder jsonBuilder = new StringBuilder();
        jsonBuilder.Append("{\"total\":" + dt.Rows.Count + ",\"rows\":[");
        for (int i = start; i < end; i++)
        {
            jsonBuilder.Append("{");
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                jsonBuilder.Append("\"");
                jsonBuilder.Append(dt.Columns[j].ColumnName);
                jsonBuilder.Append("\":\"");
                jsonBuilder.Append(dt.Rows[i][j].ToString());
                jsonBuilder.Append("\",");
            }
            jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
            jsonBuilder.Append("},");
        }
        jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
        jsonBuilder.Append("]}");
        return jsonBuilder.ToString();
    }
    /// <summary>
    /// 填充DataGrid分页的Json数据格式
    /// </summary>
    /// <param name="dt">分页数据集</param>
    /// <param name="total">总条数</param>
    /// <returns></returns>
    public static string onDataGrid(DataTable dt, int total)
    {
        StringBuilder jsonBuilder = new StringBuilder();
        jsonBuilder.Append("{\"total\":" + total + ",\"rows\":[");
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            jsonBuilder.Append("{");
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                jsonBuilder.Append("\"");
                jsonBuilder.Append(dt.Columns[j].ColumnName);
                jsonBuilder.Append("\":\"");
                jsonBuilder.Append(dt.Rows[i][j].ToString());
                jsonBuilder.Append("\",");
            }
            jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
            jsonBuilder.Append("},");
        }
        jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
        jsonBuilder.Append("]}");
        return jsonBuilder.ToString();
    }
    /// <summary>
    /// 用于初始化表单的Json数据
    /// </summary>
    /// <param name="dt">数据集,仅一条记录</param>
    /// <returns></returns>
    public static string onForm(DataTable dt)
    {
        StringBuilder jsonBuilder = new StringBuilder();
        if (dt.Rows.Count > 0)
        {
            jsonBuilder.Append("{");
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                jsonBuilder.Append("\"");
                jsonBuilder.Append(dt.Columns[j].ColumnName);
                jsonBuilder.Append("\":\"");
                jsonBuilder.Append(dt.Rows[0][j].ToString());
                jsonBuilder.Append("\",");
            }
            jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
            jsonBuilder.Append("}");
        }
        return jsonBuilder.ToString();
    }
}

/// <summary>
/// EasyUI控件可传参数
/// </summary>
public class ParamsofEasyUI
{
    public ParamsofEasyUI() { }
    public static string RequstForm(string name)
    {
        return (HttpContext.Current.Request.Form[name] == null ? string.Empty : HttpContext.Current.Request.Form[name].ToString().Trim());
    }
    public static string RequstString(string sParam)
    {
        return (HttpContext.Current.Request[sParam] == null ? string.Empty : HttpContext.Current.Request[sParam].ToString().Trim());
    }
    public static int RequstInt(string sParam)
    {
        int iValue;
        string sValue = RequstString(sParam);
        int.TryParse(sValue, out iValue);
        return iValue;
    }
    public static string order
    {
        get { return RequstString("order"); }
    }
    public static string sort
    {
        get { return RequstString("sort"); }
    }
    public static int page
    {
        get { return RequstInt("page"); }
    }
    public static int rows
    {
        get { return RequstInt("rows"); }
    }
}


 

 

目录
相关文章
|
JavaScript 测试技术
Easyui 修改jquery validatebox为英文校验提示为中文提示
Easyui 修改jquery validatebox为英文校验提示为中文提示
81 0
|
前端开发 JavaScript 数据安全/隐私保护
jQuery EasyUI简明教程
1. 背景 EasyUI虽然样式比较固定,但是功能比较全面,而且入门比较简单,适合刚刚学习前端的童鞋们,此处拿出来讲讲如何使用EasyUI。
139 0
|
JavaScript 前端开发
jQuery +easyUI 实现双击编辑
jQuery +easyUI 实现双击编辑 DataGrid 数据表里面需要加属性 editor:’text’ 才能实现 $(function(){ $('#dg').datagrid({ url:'.
2051 0
|
JavaScript 容器
jQuery EasyUI 重写datagrid的datetimebox编辑类型
jQuery EasyUI 重写datagrid的datetimebox编辑类型
1904 0
|
JavaScript 前端开发 开发者
【原】jQuery easyUI 快速搭建前端框架
jQueryEasyUI jQuery EasyUI是一组基于jQuery的UI插件集合体,而jQuery EasyUI的目标就是帮助web开发者更轻松的打造出功能丰富并且美观的UI界面。开发者不需要编写复杂的javascript,也不需要对css样式有深入的了解,开发者需要了解的只有一些简单的html标签。
1785 0