ASP.NET MVC and jqGrid 学习笔记 2-如何从本地获得数据
上回说到jqgrid的基本配置,同时演示了显示数据的一种方法——datatype: "local"。这种方法是从本地获取的,确切地说是在前端页面的javascript里写的硬编码。
本回说到的也是一种硬编码,只不过是在后台的Controller里写的,也是一种快速演示的方法,我们用ArrayList来填充数据。同时,jqgrid里要使用url参数以指定是从哪个action获得数据。
View:
1 @{ 2 ViewBag.Title = "GetDataFromLocal"; 3 } 4 5 <h2>GetDataFromLocal</h2> 6 7 <script type="text/javascript"> 8 $(function () { 9 jQuery("#grid").jqGrid({ 10 url: "/Home/GetData", 11 datatype: "json", 12 mtype:"get", 13 colNames: ['Inv No', 'Date', 'Client'], 14 colModel: [ 15 { name: 'id', index: 'id', width: 60, sorttype: "int" }, 16 { name: 'invdate', index: 'invdate', width: 90, sorttype: "date" }, 17 { name: 'name', index: 'name', width: 100 } 18 ], 19 caption: "jqGrid data", 20 rowNum: 5, 21 pager: "pager", 22 viewrecords: true, 23 width: 300, height: "auto", 24 jsonReader:{repeatitems: false} 25 }); 26 }); 27 </script> 28 29 <table id="grid"></table> 30 <div id="pager"></div>
Controller:
1 public ActionResult GetDataFromLocal() 2 { 3 return View(); 4 } 5 6 public JsonResult GetData(int? page, int? rows) 7 { //把数据放到一个动态数组里 8 ArrayList list = new ArrayList(); 9 list.Add(new { id = "1", invdate = "2007-10-01", name = "test" }); 10 list.Add(new { id = "2", invdate = "2007-10-02", name = "test" }); 11 list.Add(new { id = "3", invdate = "2007-10-02", name = "test" }); 12 list.Add(new { id = "4", invdate = "2007-10-02", name = "test" }); 13 list.Add(new { id = "5", invdate = "2007-10-02", name = "test" }); 14 list.Add(new { id = "6", invdate = "2007-10-02", name = "test" }); 15 list.Add(new { id = "7", invdate = "2007-10-02", name = "test" }); 16 list.Add(new { id = "8", invdate = "2007-10-02", name = "test" }); 17 list.Add(new { id = "9", invdate = "2007-10-02", name = "test" }); 18 list.Add(new { id = "10", invdate = "2007-10-02", name = "test" }); 19 list.Add(new { id = "11", invdate = "2007-10-02", name = "test" }); 20 list.Add(new { id = "12", invdate = "2007-10-02", name = "test" }); 21 22 var myData = list.ToArray();//便于下面用linq分页 23 24 //jqgrid的参数 25 int pageNum = page.HasValue ? page.Value : 1;//当前显示哪一页 26 int pageSize = rows.HasValue ? rows.Value : 10; //每一页显示多少条记录 27 int totalRecords = list.Count;//总记录数 28 int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);//总页数 29 var jsonData = new 30 { 31 total = totalPages, 32 page = pageNum, 33 records = totalRecords, 34 rows = myData.Skip((pageNum - 1) * pageSize).Take(pageSize)//分页 35 }; 36 37 return Json(jsonData, JsonRequestBehavior.AllowGet); 38 }
--End--