在ASP.NET MVC中使用JQ插件datatable
1. Models
public class Citys { public int Id { get; set; } public string CityName { get; set; } public int ZipCode { get; set; } }
2. Controller
public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult GetJsonCitys(int? secho) { var cityList = new List<Citys>(); for (int i = 0; i < 100; i++) { cityList.Add(new Citys { Id = i, CityName = Guid.NewGuid().ToString(), ZipCode = DateTime.Now.Millisecond }); } var objs = new List<object>(); foreach (var city in cityList) { objs.Add(GetPropertyList(city).ToArray()); } return Json(new { sEcho = secho, iTotalRecords = cityList.Count(), aaData = objs }, JsonRequestBehavior.AllowGet); } private List<string> GetPropertyList(object obj) { var propertyList = new List<string>(); var properties = obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); foreach (var property in properties) { object o = property.GetValue(obj, null); propertyList.Add(o == null ? "" : o.ToString()); } return propertyList; } }
3. Views
@{ Layout = null; } <!DOCTYPE html> <html> <head> <title>Index</title> <link href="@Url.Content("~/Style/demo_page.css")" rel="stylesheet" type="text/css" /> <link href="@Url.Content("~/Style/jquery-ui-1.8.4.custom.css")" rel="stylesheet" type="text/css" /> <link href="@Url.Content("~/Style/demo_table_jui.css")" rel="stylesheet" type="text/css" /> <script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/Plug-in/jquery.dataTables.js")" type="text/javascript"></script> <script type="text/javascript" charset="utf-8"> $(document).ready(function () { $('#DataTable').dataTable({ "oLanguage": {//语言国际化 "sUrl": "/Scripts/Plug-in/jquery.dataTable.cn.txt" }, "bJQueryUI": true, "sPaginationType": "full_numbers", 'bPaginate': true, //是否分页。 "bProcessing": true, //当datatable获取数据时候是否显示正在处理提示信息。 "bServerSide": false, "sAjaxSource": "Home/GetJsonCitys", "aoColumns": [ { "sTitle": "编号", "sClass": "center" }, { "sTitle": "城市名称", "sClass": "center" }, { "sTitle": "邮政编码", "sClass": "center" }, { "sTitle": "操作", "sClass": "center", "fnRender": function (obj) { return '<a href=\"Details/' + obj.aData[0] + '\">查看详情</a> <input tag=\"' + obj.aData[0] + '\" type=\"checkbox\" name=\"name\" />'; } } ] }); }); //aoColumns 参数用来定义表格的列,这是一个数组,其中的每一个对象用来定义一列。 //对于每一个列对象: sTitle 定义列的标题 sClass 定义列的样式 //fnRender 函数用来渲染列,这个函数将会传递一个参数对象,这个参数对象的 iDataColumn 属性表示当前的列索引,aData 表示当前的行数组。函数返回的结果将被填充到单元格中。 //当然了,对于表示行的数组来说,长度应该是相同的。如果某一行数据缺失或者提供了过多地数据的话,就会得到一个警告。 </script> </head> <body style="font-size: 12px;"> <table class="display" id="DataTable"> <thead> <tr> <th> Id </th> <th> CityName </th> <th> ZipCode </th> <th> 操作 </th> </tr> </thead> <tbody> </tbody> </table> </body> </html>
例子下载:
http://down.51cto.com/data/892223