jQuery EasyUI DataGrid在MVC中的运用-基本属性并实现分页

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了jQuery EasyUI DataGrid在MVC中的运用-基本属性并实现分页相关的知识,希望对你有一定的参考价值。

※ datagrid的基本属性和方法 
※ datagrid分页在前后台的实现

最终效果: 
技术分享  与视图显示对应的view model

 
public class Book
        public string ItemId { get; set; }
        public string ProductId { get; set; }
        public decimal ListPrice { get; set; }
        public decimal UnitCost { get; set; }
        public string Attr1 { get; set; }
        public Int16 Status { get; set; }
  模拟一个从数据库拿数据,并考虑分页的服务层方法

 

□ 与分页有关的类

public class PageParam
        public int PageSize { get; set; } 
        public int PageIndex { get; set; } 
在实际项目中,可以把以上作为一个基类,把各个领域的各种搜索条件封装成继承PageParam的子类。

 

□ 分页服务层方法

using System.Linq;
using DataGridInMvc.Models;
using System.Collections.Generic;
using Microsoft.Ajax.Utilities;

namespace DataGridInMvc.Helper
{
    public class BookService
    {
        public IEnumerable<Book> LoadPageBookData(PageParam param, out int total)
        {
            //创建Book的集合
            var books = new List<Book>();
            for (int i = 0; i < 30; i++)
            {
                books.Add(new Book()
                {
                    ItemId = "EST-" + i,
                    ProductId = "AV-SB-" + i,
                    ListPrice = (i + 5) * 10m,
                    UnitCost = (i + 2) * 10m,
                    Attr1 = "Attr" + i,
                    Status = (short)0
                });
            }

            total = books.Count();
            var result = books.OrderBy(b => b.ItemId)
                .Skip(param.PageSize*(param.PageIndex - 1))
                .Take(param.PageSize);
            return result;
        }
    }

  Controller有显示页面和响应前台datagrid请求的Action方法

using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Web;
using System.Web.Mvc;
using DataGridInMvc.Helper;
using DataGridInMvc.Models;

namespace DataGridInMvc.Controllers
{
    public class HomeController : Controller
    {

        public ActionResult Index() { return View();
        }

        public ActionResult GetData()
        {
            //接收datagrid传来的参数
            int pageIndex = int.Parse(Request["page"]);
            int pageSize = int.Parse(Request["rows"]);

            //构建得到分页数据方法所需的参数
            var temp = new PageParam()
            {
                PageIndex = pageIndex,
                PageSize = pageSize
            };

            //分页数据方法的输出参数
            int totalNum = 0;

            var service = new BookService();
            var books = service.LoadPageBookData(temp, out totalNum);

            var result = from book in books
                select new {book.ItemId, book.ProductId, book.ListPrice, book.UnitCost, book.Status, book.Attr1};

            //total,rows是前台datagrid所需要的
            var jsonResult = new {total = totalNum, rows = result};

            //把json对象序列化成字符串
            string str = JsonSerializeHelper.SerializeToJson(jsonResult);
            return Content(str);
        }
    }
}      

□ 这里需要把json对象序列化成string,使用Newtonsoft组件是不错的选择。把序列化和反序列化封装成类。

using System; using Newtonsoft.Json; namespace DataGridInMvc.Helper { public static class JsonSerializeHelper { /// <summary> /// 把object对象序列化成json字符串 /// </summary> /// <param name="obj">序列话的实例</param> /// <returns>序列化json字符串</returns> public static string SerializeToJson(object obj) { return JsonConvert.SerializeObject(obj); } /// <summary> /// 把json字符串反序列化成Object对象 /// </summary> /// <param name="json">json字符串</param> /// <returns>对象实例</returns> public static Object DeserializeFromJson(string json) { return JsonConvert.DeserializeObject(json); } /// <summary> /// 把json字符串反序列化成泛型T /// </summary> /// <typeparam name="T">泛型</typeparam> /// <param name="json">json字符串</param> /// <returns>泛型T</returns> public static T DeserializeFromJson<T>(string json) { return JsonConvert.DeserializeObject<T>(json); } } } 

  视图

<link href="~/Content/themes/default/easyui.css" rel="stylesheet" /> <link href="~/Content/themes/icon.css" rel="stylesheet" /> <script src="~/Scripts/jquery-1.10.2.js"></script> <script src="~/Scripts/jquery.easyui.min.js"></script> <script src="~/Scripts/easyui-lang-zh_CN.js"></script> <script type="text/javascript"> $(function() { initData(); }); function initData() { $(‘#tt‘).datagrid({ url: ‘Home/GetData‘, width: 500, height: 350, title: ‘Book列表‘, iconCls: ‘icon-save‘, fitColumns: true, rownumbers: true, //是否加行号 pagination: true, //是否显式分页 pageSize: 15, //页容量,必须和pageList对应起来,否则会报错 pageNumber: 2, //默认显示第几页 pageList: [15, 30, 45],//分页中下拉选项的数值 columns: [[ //book.ItemId, book.ProductId, book.ListPrice, book.UnitCost, book.Status, book.Attr1 { field: ‘ItemId‘, title: ‘主键‘, sortable: true }, { field: ‘ProductId‘, title: ‘产品编号‘ }, { field: ‘Attr1‘, title: ‘属性‘ }, { field: ‘UnitCost‘, title: ‘成本价‘ }, { field: ‘ListPrice‘, title: ‘零售价‘ }, { field: ‘Status‘, title: ‘状态‘ }, ]] }); } function changeP() { var dg = $(‘#tt‘); dg.datagrid(‘loadData‘, []); //重新加载数据 dg.datagrid({ pagePosition: $(‘#p-pos‘).val() }); //分页位置 dg.datagrid(‘getPager‘).pagination({ //分页样式、内容 layout: [‘list‘, ‘sep‘, ‘first‘, ‘prev‘, ‘sep‘, $(‘#p-style‘).val(), ‘sep‘, ‘next‘, ‘last‘, ‘sep‘, ‘refresh‘] }); } </script> <p> 选择分页显示位置: <select id="p-pos" onchange="changeP()"> <option>bottom</option> <option>top</option> <option>both</option> </select> 选择分页显示样式 <select id="p-style" onchange="changeP()"> <option>manual</option> <option>links</option> </select> </p> <table id="tt"> </table>

※ datagrid的基本属性和方法 
※ datagrid分页在前后台的实现

最终效果: 
技术分享  与视图显示对应的view model

 
public class Book
        public string ItemId { get; set; }
        public string ProductId { get; set; }
        public decimal ListPrice { get; set; }
        public decimal UnitCost { get; set; }
        public string Attr1 { get; set; }
        public Int16 Status { get; set; }
  模拟一个从数据库拿数据,并考虑分页的服务层方法

 

□ 与分页有关的类

public class PageParam
        public int PageSize { get; set; } 
        public int PageIndex { get; set; } 
在实际项目中,可以把以上作为一个基类,把各个领域的各种搜索条件封装成继承PageParam的子类。

 

□ 分页服务层方法

using System.Linq;
using DataGridInMvc.Models;
using System.Collections.Generic;
using Microsoft.Ajax.Utilities;

namespace DataGridInMvc.Helper
{
    public class BookService
    {
        public IEnumerable<Book> LoadPageBookData(PageParam param, out int total)
        {
            //创建Book的集合
            var books = new List<Book>();
            for (int i = 0; i < 30; i++)
            {
                books.Add(new Book()
                {
                    ItemId = "EST-" + i,
                    ProductId = "AV-SB-" + i,
                    ListPrice = (i + 5) * 10m,
                    UnitCost = (i + 2) * 10m,
                    Attr1 = "Attr" + i,
                    Status = (short)0
                });
            }

            total = books.Count();
            var result = books.OrderBy(b => b.ItemId)
                .Skip(param.PageSize*(param.PageIndex - 1))
                .Take(param.PageSize);
            return result;
        }
    }

  Controller有显示页面和响应前台datagrid请求的Action方法

using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Web;
using System.Web.Mvc;
using DataGridInMvc.Helper;
using DataGridInMvc.Models;

namespace DataGridInMvc.Controllers
{
    public class HomeController : Controller
    {

        public ActionResult Index() { return View();
        }

        public ActionResult GetData()
        {
            //接收datagrid传来的参数
            int pageIndex = int.Parse(Request["page"]);
            int pageSize = int.Parse(Request["rows"]);

            //构建得到分页数据方法所需的参数
            var temp = new PageParam()
            {
                PageIndex = pageIndex,
                PageSize = pageSize
            };

            //分页数据方法的输出参数
            int totalNum = 0;

            var service = new BookService();
            var books = service.LoadPageBookData(temp, out totalNum);

            var result = from book in books
                select new {book.ItemId, book.ProductId, book.ListPrice, book.UnitCost, book.Status, book.Attr1};

            //total,rows是前台datagrid所需要的
            var jsonResult = new {total = totalNum, rows = result};

            //把json对象序列化成字符串
            string str = JsonSerializeHelper.SerializeToJson(jsonResult);
            return Content(str);
        }
    }
}      

□ 这里需要把json对象序列化成string,使用Newtonsoft组件是不错的选择。把序列化和反序列化封装成类。

using System; using Newtonsoft.Json; namespace DataGridInMvc.Helper { public static class JsonSerializeHelper { /// <summary> /// 把object对象序列化成json字符串 /// </summary> /// <param name="obj">序列话的实例</param> /// <returns>序列化json字符串</returns> public static string SerializeToJson(object obj) { return JsonConvert.SerializeObject(obj); } /// <summary> /// 把json字符串反序列化成Object对象 /// </summary> /// <param name="json">json字符串</param> /// <returns>对象实例</returns> public static Object DeserializeFromJson(string json) { return JsonConvert.DeserializeObject(json); } /// <summary> /// 把json字符串反序列化成泛型T /// </summary> /// <typeparam name="T">泛型</typeparam> /// <param name="json">json字符串</param> /// <returns>泛型T</returns> public static T DeserializeFromJson<T>(string json) { return JsonConvert.DeserializeObject<T>(json); } } } 

  视图

<link href="~/Content/themes/default/easyui.css" rel="stylesheet" /> <link href="~/Content/themes/icon.css" rel="stylesheet" /> <script src="~/Scripts/jquery-1.10.2.js"></script> <script src="~/Scripts/jquery.easyui.min.js"></script> <script src="~/Scripts/easyui-lang-zh_CN.js"></script> <script type="text/javascript"> $(function() { initData(); }); function initData() { $(‘#tt‘).datagrid({ url: ‘Home/GetData‘, width: 500, height: 350, title: ‘Book列表‘, iconCls: ‘icon-save‘, fitColumns: true, rownumbers: true, //是否加行号 pagination: true, //是否显式分页 pageSize: 15, //页容量,必须和pageList对应起来,否则会报错 pageNumber: 2, //默认显示第几页 pageList: [15, 30, 45],//分页中下拉选项的数值 columns: [[ //book.ItemId, book.ProductId, book.ListPrice, book.UnitCost, book.Status, book.Attr1 { field: ‘ItemId‘, title: ‘主键‘, sortable: true }, { field: ‘ProductId‘, title: ‘产品编号‘ }, { field: ‘Attr1‘, title: ‘属性‘ }, { field: ‘UnitCost‘, title: ‘成本价‘ }, { field: ‘ListPrice‘, title: ‘零售价‘ }, { field: ‘Status‘, title: ‘状态‘ }, ]] }); } function changeP() { var dg = $(‘#tt‘); dg.datagrid(‘loadData‘, []); //重新加载数据 dg.datagrid({ pagePosition: $(‘#p-pos‘).val() }); //分页位置 dg.datagrid(‘getPager‘).pagination({ //分页样式、内容 layout: [‘list‘, ‘sep‘, ‘first‘, ‘prev‘, ‘sep‘, $(‘#p-style‘).val(), ‘sep‘, ‘next‘, ‘last‘, ‘sep‘, ‘refresh‘] }); } </script> <p> 选择分页显示位置: <select id="p-pos" onchange="changeP()"> <option>bottom</option> <option>top</option> <option>both</option> </select> 选择分页显示样式 <select id="p-style" onchange="changeP()"> <option>manual</option> <option>links</option> </select> </p> <table id="tt"> </table>

以上是关于jQuery EasyUI DataGrid在MVC中的运用-基本属性并实现分页的主要内容,如果未能解决你的问题,请参考以下文章

jQuery EasyUI datagrid 删除多行

jQuery easyUI easyui-datagrid 选中指定内容的行

jQuery EasyUI教程之datagrid应用

jquery easyui datagrid使用参考

jQuery EasyUI教程之datagrid应用

jQuery EasyUI教程之datagrid应用