界面演示:
Controller:
public ActionResult F1() { DataTable dt = new DataTable(); DataColumn dc1 = new DataColumn("ID",Type.GetType("System.Int32")); DataColumn dc2 = new DataColumn("Name", Type.GetType("System.String")); DataColumn dc3 = new DataColumn("Age", Type.GetType("System.Int32")); dt.Columns.Add(dc1); dt.Columns.Add(dc2); dt.Columns.Add(dc3); for (int i = 0; i < 5; i++) { DataRow dr = dt.NewRow(); dr["ID"] = i; dr["Name"] = "张三"; dr["Age"] = (i+i+1)*2; dt.Rows.Add(dr); } /* List<Person> lp = new List<Person>() { new Person() {Id=1,Name="张三",Age=14 }, new Person() {Id=2,Name="李四",Age=14 }, new Person() {Id=3,Name="王五",Age=14 }, }; object[] obj = new object[lp.Count]; for (int i = 0; i < lp.Count; i++) { obj[i] = lp[i]; } */ ViewBag.Data = Newtonsoft.Json.JsonConvert.SerializeObject(dt); return View(); }
view:(参考:http://www.itxst.com/ag-grid/tutorial.html)
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>ag-grid单行选中</title> <script src="//www.itxst.com/package/ag-grid/ag-grid-community.js"></script> <link href="//www.itxst.com/package/ag-grid/styles/ag-grid.css" rel="stylesheet" /> </head> <body> <input value="获取选中数据" type="button" onclick="getSelect()"> <div id="myGrid" style="width: 100%;height: 500px;" class="ag-theme-balham"></div> <script> //定义表格列 var columnDefs = [ { headerName: ‘编号‘, field: ‘ID‘,‘pinned‘: ‘left‘, filter: ‘agTextColumnFilter‘,checkboxSelection:true,headerCheckboxSelection:true }, { headerName: ‘姓名‘, field: ‘Name‘ }, { headerName: ‘年龄‘, field: ‘Age‘ , filter: ‘agNumberColumnFilter‘} ]; //与列对应的数据; 属性名对应上面的field var data =@Html.Raw(@ViewBag.Data) ; //必须用@Html.Raw 否则无法解析 var gridOptions = { columnDefs: columnDefs, rowSelection: ‘multiple‘, //设置多行选中 rowMultiSelectWithClick:true, rowDeselection:true, rowData: data }; var ag=null; //在dom加载完成后 初始化agGrid完成 document.addEventListener("DOMContentLoaded", function () { var eGridDiv = document.querySelector(‘#myGrid‘); ag=new agGrid.Grid(eGridDiv, gridOptions); }); function getSelect() { alert(JSON.stringify(gridOptions.api.getSelectedRows())); } </script> </body> </html>