引用了:https://blog.csdn.net/h273979586/article/details/77913896 的解決方式
<!-- 初始化 DataTables --> <script> $(document).ready(function () { $('#example').dataTable({ "bPaginate": true, ajax: { //調用URL中的ACTION方法 url: '@Url.Action("GetAllData", "AjaxTest")', }, columns: [ { "name": "Title", "data": "Title", }, { "name": "ReleaseDate", "data": "ReleaseDate" }, { "name": "Genre", "data": "Genre", }, { "name": "Price", "data": "Price", }, { "name": "Rating", "data": "Rating", } ] }); }); </script>
第二部分:URL調用的ACTION方法中返回Json數據
public JsonResult GetAllData() { var MoviesData = new List<Movie>(); //獲取所有內容 var movies = from m in db.Movies select m; foreach (var item in movies.ToList()) { MoviesData.Add(item); } //返回json數據到Index界面 return Json(new { iTotalRecords = MoviesData.Count(), iTotalDisplayRecords = MoviesData.Count(), data = MoviesData }, JsonRequestBehavior.AllowGet); }
<script> $(document).ready(function () { $('#example').dataTable({ "bPaginate": true, ajax: { url: '@Url.Action("GetAllData", "AjaxTest")', }, columns: [ { "name": "Title", "data": "Title", }, { "name": "ReleaseDate", "data": "ReleaseDate", //電影上映日期的格式修改 "render": function ChangeDateFormat(cellval) { var date = new Date(parseInt(cellval.replace("/Date(", "").replace(")/", ""), 10)); var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1; var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate(); return date.getFullYear() + "-" + month + "-" + currentDate; } }, { "name": "Genre", "data": "Genre", }, { "name": "Price", "data": "Price", }, { "name": "Rating", "data": "Rating", } ] }); }); </script>