【发布时间】:2019-09-22 03:23:12
【问题描述】:
(Model Class) 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; }
}
Controller ActionResult它从EmployeeGetClass获取数据
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>
这是我实现 dataTable 的 Ajax 调用,但它显示的不是 DataTable 形式的 JSON 类型数据。
我使用这两个库来实现这个Datatable:
//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>
}
【问题讨论】:
-
您是否在视图中添加
jquery.js? -
调用
/Home/Index的实际结果是什么样的? -
我没有在视图中添加 jquery.js
-
实际结果是 json 类型的数据,例如 "data":[{"Employee_id":1,"Name":"Muhammad Ali","Contact":"03457845130","Salary":5400} ,{"Employee_id":2,"Name":"Sawood","Contact":"03451240114","Salary":5800},
标签: c# ajax asp.net-mvc datatable datatables