Employee
的(模型类)模型类
public class Employee
{
public int Employee_id { get; set; }
public string Name { get; set; }
public string Contact { get; set; }
public int Salary { get; set; }
}
控制器ActionResult ,它从EmployeeGet
类获取数据
public ActionResult Index()
{
EmployeeGet empgetObj = new EmployeeGet();
var getRecord = empgetObj.GetAllEmployees();
return Json(new{ data = getRecord}, JsonRequestBehavior.AllowGet);
}
通过查询从数据库获取记录的类
public class EmployeeGet
{
string connString = (@"Data Source=DESKTOP-PK5A6U3\SQLEXPRESS;Initial Catalog = TableImplemented; Integrated Security = True");
public List<Employee> GetAllEmployees()
{
List<Employee> employees = new List<Employee>();
using (SqlConnection conn = new SqlConnection(connString))
{
var query = "select * from Employee";
using (SqlCommand cmd = new SqlCommand(query, conn))
{
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Employee employee = new Employee();
employee.Employee_id = Convert.ToInt32(rdr["Employee_id"]);
employee.Name = rdr["Name"].ToString();
employee.Contact = rdr["Contact"].ToString();
employee.Salary = Convert.ToInt32(rdr["Salary"]);
employees.Add(employee);
}
conn.Close();
}
}
return employees;
}
}
索引视图在此视图中,我实现了表
@{
ViewBag.Title = "Home Page";
}
<table id="tbleID" width="90%" class="display">
<thead>
<tr>
<th>Employee_id</th>
<th>Name</th>
<th>Contact</th>
<th>Salary</th>
</tr>
</thead>
</table>
这是我的Ajax调用,用于实现dataTable
,但它显示的不是DataTable形式的JSON类型数据。
我使用了这两个库来实现此数据表:
// cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css“ // cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js
<link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet" />
@section Scripts{
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script>
(function ($) {
debugger;
$("#tbleID").DataTable(
{
'ajax': {
'url': '/Home/Index',
'type': 'GET',
'contentType':"application/json; charset=utf-8",
'dataType': 'json',
},
'columns':
[
{ 'data': 'Employee_id', 'autoWidth': true },
{ 'data': 'Name', 'autoWidth': true },
{ 'data': 'Contact', 'autoWidth': true },
{ 'data': 'Salary', 'autoWidth': true }
]
});
});
</script>
}
答案 0 :(得分:0)
首先,您只需要返回json数据
return Json(getRecord);
第二,您可以从中更改您的js代码
(function ($) {
进入此
(function() {
更新js代码
$("#tbleID").DataTable(
{
'ajax': '/Home/Index',
'columns':
[
{ 'data': 'Employee_id', 'autoWidth': true },
{ 'data': 'Name', 'autoWidth': true },
{ 'data': 'Contact', 'autoWidth': true },
{ 'data': 'Salary', 'autoWidth': true }
]
});
请告诉我,以便我编辑答案