Easyui-DataGrid 查询,类序列化(构造匿名对象)

来源:互联网 发布:医保 车祸 知乎 编辑:程序博客网 时间:2024/05/16 16:21

视图

Index视图

@{    Layout = null;}<!DOCTYPE html><html><head>    <meta name="viewport" content="width=device-width" />    <meta charset="UTF-8">    <title>DataGrid的使用示例</title>    <link href="~/Easyui/jquery-easyui/themes/default/easyui.css" rel="stylesheet" />    <link href="~/Easyui/jquery-easyui/themes/icon.css" rel="stylesheet" />    <link href="~/Easyui/jquery-easyui/demo/demo.css" rel="stylesheet" />    <script src="~/Easyui/jquery-easyui/jquery.min.js"></script>    <script src="~/Easyui/jquery-easyui/jquery.easyui.min.js"></script></head><body>    <table id="dg" title="MyUsers" class="easyui-datagrid" spellcheck="" style="width:700px;height:320px"           url="/Home/GetData"           toolbar="#toolbar"           pagination="true" @*在datagrid 组件底部显示分页工具栏。默认为false*@           pagelist="[2,5,8,10]" @*设置每页可以选择显示2条数据,或5条数据,或8条数据,或10条数据*@           pagenumber="1" @*设置初始页为第一页*@           pagesize="8" @*设置每页显示8条数据*@           rowstyler="setRowStyler" @*对某一行设置样式*@           rownumbers="true" @*显示行号*@           fitcolumns="true" @*是否自动展开或收缩,以达到自适应。默认为false。*@           singleselect="true" @*设置true,只能选定一行。默认为false。*@>        <thead>            <tr>                <!--<th data-options="field:'Name'"  data-options="width:50">姓名</th>  这是完整的写法,以下是简写-->                <th field="Name" width="50" styler="setColuStyler">姓名 </th>                <th field="Age" width="50" sortable="true" formatter="formatAge">年龄</th>  <!--formatter="formatAge"是调用formatAge函数对这一列的值进行格式化-->                <th field="Phone" width="50">电话</th>                <th field="Email" width="50">邮箱</th>            </tr>        </thead>    </table>        <div id="toolbar" style="padding:3px">        <div>            <a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true">增加</a>            <a href="#" class="easyui-linkbutton" iconcls="icon-edit" plain="true">编辑</a>            <a href="#" class="easyui-linkbutton" iconcls="icon-remove" plain="true">删除</a>        </div>        <div>            <span>姓名</span>            <input id="searchName" style="line-height:20px;border:1px solid #ccc">            <a href="#" class="easyui-linkbutton" plain="true" iconcls="icon-search" onclick="doSearch()">查询</a>        </div>    </div>      </body></html> <script type="text/javascript">     function doSearch() {         $('#dg').datagrid('load', {                          searchName: $('#searchName').val() //根据姓名来查询数据。这里将搜索框的内容作为查询条件                    });     }     //value:当前列对应字段值。row:当前的行记录数据。index:当前的行下标     function formatAge(value, row,index)     {         if (value >= 26) {             return '<span style="color:red;">' + value + '</span>';         }         else {             return value;         }     }     //给名字为周晶的那一行添加样式        function setRowStyler(index, row) //参数: index 索引,row 对象     {         //console.log(row);         if (row.Name == '周晶')         {             return "background-color:Orange";         }     }     //给名字为黄雪辉的那一列添加样式       function setColuStyler(value, row, index) //参数: value 值,row对象,index 索引。     {         if (row.Name == "黄雪辉")         {             return "background-color:Violet";         }     } </script>


Demo视图 

@{    Layout = null;}<!DOCTYPE html><html><head>    <meta name="viewport" content="width=device-width" />    <title>DataGrid的使用示例</title>    <link href="~/Easyui/jquery-easyui/themes/default/easyui.css" rel="stylesheet" />    <link href="~/Easyui/jquery-easyui/themes/icon.css" rel="stylesheet" />    <link href="~/Easyui/jquery-easyui/demo/demo.css" rel="stylesheet" />    <script src="~/Easyui/jquery-easyui/jquery.min.js"></script>    <script src="~/Easyui/jquery-easyui/jquery.easyui.min.js"></script></head><body>    <table id="dg"></table>    <div id="toolbar" style="padding:3px">        <div>            <a href="#" class="easyui-linkbutton" iconcls="icon-add" plain="true">增加</a>            <a href="#" class="easyui-linkbutton" iconcls="icon-edit" plain="true">编辑</a>            <a href="#" class="easyui-linkbutton" iconcls="icon-remove" plain="true">删除</a>            <span>姓名</span>            <input id="searchName" style="line-height:20px;border:1px solid #ccc">            <a href="#" class="easyui-linkbutton" plain="true" iconcls="icon-search" onclick="doSearch()">查询</a>        </div>    </div></body></html><!--DataGrid 是扩展自Panel面板,所有Panel的属性DataGrid是可以使用的--><script type="text/javascript">    $(function () {        $("#dg").datagrid({            title: "MyUsers",            width: 800,            height: 320,            iconCls: 'icon-search', //在标题前面加一个搜索图标            pagination: true,            pageList: [2, 5, 8, 10],            pageNumber: 1,            url: "/Home/GetData",            sortName: 'Age',            sortOrder: 'ASC',            toolbar: "#toolbar",            //toolbar:            //    [            //        { text: "新增", iconCls: 'icon-add', handler: function () { alert("新增") } },            //        { text: "编辑", iconCls: 'icon-edit', handler: function () { alert("编辑") } },            //        { text: "新增", iconCls: 'icon-remove', handler: function () { alert("删除") } },            //    ],            columns: [[                { title: '姓名', field: 'Name', width: 200, sortable: true },                { title: '年龄', field: 'Age', width: 200 },                { title: '电话', field: 'Phone', width: 200 },                { title: '邮箱', field: 'Email', width: 200 },            ]]        })    })    function doSearch() {        $("#dg").datagrid("load", {            searchName: $("#searchName").val()        })    }</script>


Home控制器

using MVC.Easyui.Models;using System;using System.Collections.Generic;using System.Linq;using System.Linq.Expressions;using System.Web;using System.Web.Mvc;using System.Web.Script.Serialization;namespace MVC.Easyui.Controllers{    public class HomeController : Controller    {        //进入视图-->HTML的写法        public ActionResult Index()        {            return View();        }        //进入视图-->JS的写法        public ActionResult Demo()        {            return View();        }        public ActionResult Test()        {            return View();        }        //视图页面的Easyui-DataGrid通过异步请求数据        public string GetData(FromData fd)        {            salesEntities1 db = new salesEntities1();            int count = db.T_UserInfo.Count();            //根据指定的字段来进行排序            //var list = db.T_UserInfo.AsEnumerable().OrderBy(p => GetPropertyValue(p, fd.sort)).Skip((fd.page - 1) * (fd.rows)).Take(fd.rows).ToList();            var list = db.T_UserInfo.AsEnumerable();            //如果用户设置了排序(即:传递了sort和order参数过来)sort表示要排序的字段,order表示升序还是降序排序            if (!string.IsNullOrEmpty(fd.sort) && !string.IsNullOrEmpty(fd.order))            {                //根据指定字段来排序并分页                if (fd.order == "DESC")                {                    list = list.OrderByDescending(r => r.GetType().GetProperty(fd.sort).GetValue(r)).Skip((fd.page - 1) * fd.rows).Take(fd.rows).AsQueryable();                }                else                {                    list = list.OrderBy(r => r.GetType().GetProperty(fd.sort).GetValue(r)).Skip((fd.page - 1) * fd.rows).Take(fd.rows).AsQueryable();                }            }            else            {                 list=list.OrderBy(r=>r.Id).Skip((fd.page - 1) * fd.rows).Take(fd.rows).AsQueryable();            }            //如果搜索框的内容不为空,就进行搜索查询            if (!string.IsNullOrEmpty(fd.searchName))            {                list = list.Where(r => r.Name.Contains(fd.searchName));//模糊查询            }            var x = new            {                total = count,                rows = list.Select(r => new   //在这里来构建匿名类对象                {                    Name = r.Name,                    Age = r.Age,                    Phone = r.Mobile,                    Email = r.Email                })            };            //使用Jil.JSON.Serialize()来对对象序列化需要通过安装插件 PM> Install-Package Jil -version 2.10.0            var strJson = Jil.JSON.Serialize(x);            return strJson;        }        /*        /// <summary>        /// 根据传递进来的对象+对象的某个属性来返回指定对象的该属性值        /// </summary>        /// <param name="obj">传入类型对象</param>        /// <param name="property">对象的某个属性</param>        /// <returns>返回指定对象的该属性值</returns>        private object GetPropertyValue(object obj, string property)        {            System.Reflection.PropertyInfo propertyInfo = obj.GetType().GetProperty(property);            return propertyInfo.GetValue(obj, null);        }*/    }    //用于接收从视图传递过来的表单参数    public class FromData    {        //当前页        public int page { get; set; }        //页大小        public int rows { get; set; }        //搜索的姓名        public string searchName { get; set; }        //按哪个字段进行排序        public string sort { get; set; }        //排序方式(DESC ,ASC)        public string order { get; set; }    }}


特别注意:

Easyui-DataGrid 接收的是一下格式的Json对象,或字符串。所有我们需要将对象序列化成下面格式的Json字符串,或者Json对象

{"total":28,"rows":[{"productid":"FI-SW-01","productname":"Koi","unitcost":10.00,"status":"P","listprice":36.50,"attr1":"Large","itemid":"EST-1"},{"productid":"K9-DL-01","productname":"Dalmation","unitcost":12.00,"status":"P","listprice":18.50,"attr1":"Spotted Adult Female","itemid":"EST-10"},{"productid":"RP-SN-01","productname":"Rattlesnake","unitcost":12.00,"status":"P","listprice":38.50,"attr1":"Venomless","itemid":"EST-11"},{"productid":"RP-SN-01","productname":"Rattlesnake","unitcost":12.00,"status":"P","listprice":26.50,"attr1":"Rattleless","itemid":"EST-12"},{"productid":"RP-LI-02","productname":"Iguana","unitcost":12.00,"status":"P","listprice":35.50,"attr1":"Green Adult","itemid":"EST-13"},{"productid":"FL-DSH-01","productname":"Manx","unitcost":12.00,"status":"P","listprice":158.50,"attr1":"Tailless","itemid":"EST-14"},{"productid":"FL-DSH-01","productname":"Manx","unitcost":12.00,"status":"P","listprice":83.50,"attr1":"With tail","itemid":"EST-15"},{"productid":"FL-DLH-02","productname":"Persian","unitcost":12.00,"status":"P","listprice":23.50,"attr1":"Adult Female","itemid":"EST-16"},{"productid":"FL-DLH-02","productname":"Persian","unitcost":12.00,"status":"P","listprice":89.50,"attr1":"Adult Male","itemid":"EST-17"},{"productid":"AV-CB-01","productname":"Amazon Parrot","unitcost":92.00,"status":"P","listprice":63.50,"attr1":"Adult Male","itemid":"EST-18"}]}




0 0
原创粉丝点击