1

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; }
}
1
  • What is your specific question about your code? As it stands, this seems too broad to me. Commented Aug 9, 2018 at 10:15

1 Answer 1

2

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
            }
            ] 
    });
});
Sign up to request clarification or add additional context in comments.

1 Comment

Worked as charm.. Thanks bro :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.