jQuery 使用 ajax (asp.net,mvc) 加载数据表

jQuery DataTable loading using ajax (asp.net,mvc)

我正在尝试使用 web.api

加载 DataTable

我的 HTML 代码如下

    <button id="refresh">Refresh</button>
    <button id="AddRow">Add New Row</button>
    <table id="stdTable" class="table table-bordered table-striped" width="100%">
        <thead>
            <tr>
                <th>Id</th>
                <th>Name</th>
                <th>Age</th>
                <th>Date of birth</th>
                <th>Edit/View</th>
            </tr>
        </thead>
    </table>

我的模态如下

public class StudentModel {
    [Key]
    public int Id { get; set; }
    public String Name { get; set; }
    public int Age { get; set; }
    public DateTime DateofBirth { get; set; }
}

请按照以下步骤操作

  1. 安装 NeGet 包 "jquery.datatables" 我正在使用 v 1.10.12

  2. 添加 web API 控制器和如下添加方法

</p> <pre><code> [HttpGet] public IHttpActionResult LoadStudents() { using (AppDbContext db = new AppDbContext()) { var s = db.Studets.ToList(); var json = JsonConvert.SerializeObject(s); string yourJson = json; var response = this.Request.CreateResponse(HttpStatusCode.OK); response.Content = new StringContent( yourJson, Encoding.UTF8, "application/json"); return ResponseMessage(response); } }

jQuery 脚本如下

 $(document).ready(function () {
    $('#stdTable').DataTable({
        processing: true,
        serverSide: false,
        ordering: true,
        paging: true,
        searching: true,
        columns: [
           { title: "Id" },
           { title: "Name" },
           { title: "Age" },
           { title: "DateofBirth" },
           { title: "View Data" }
        ],
        columns: [
          { data: "Id" },
          { data: "Name" },
          { data: "Age" },
          { data: "DateofBirth" },
          {
              data: null,
              defaultContent: "<button class='tblview'>View Id</button><button class='tblDelete'>Delete</button>"
          }
        ],
        ajax: {
            "url": "api/Your/ApiUrl",
            "type": "GET",
            "dataSrc": ''
        },
        "columnDefs": [
            {
                "targets": 0,
                "visible": false
            }
            ] 
    });
});