Nicol Vishan
Nicol Vishan

Reputation: 63

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

I am trying to load DataTable using web.api

My HTML code as bellow

    <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>

My modal as bellow

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

Upvotes: 1

Views: 3603

Answers (1)

Udara Kasun
Udara Kasun

Reputation: 2216

Please follow bellow steps

  1. Install NeGet Package "jquery.datatables" i am using v 1.10.12

  2. Add web API controller and Add method as bellow

 [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 Script as bellow

 $(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
            }
            ] 
    });
});

Upvotes: 2

Related Questions