Backend For Loading Table with Ajax

Backend For Loading Table with Ajax

burgoyneburgoyne Posts: 7Questions: 3Answers: 0

Hey everyone,
I have my table working client-side, but it is getting really slow (~30 seconds to load), so I am switching from loading from the dom, to using ajax.

My issue is I'm not sure exactly what is needed on the backend? I currently get an array of all the postings (that is what populates the table), convert it to json, and return that:

var postingVMs = (await _adminServices.GetAllPostings())
                        .ToViewModels().ToArray();

                    var json = new JsonResult(new { post = postingVMs });

                    return View("Postings", json);

Here is my javascript:

$('#datatable-localized').DataTable({
                ajax: {
                    url: "/Admin/Postings", //edit when new method is implemented
                    method: "GET"
                },
                deferRender: true,
                orderClasses: false,
                responsive: true,

Now on a side note, I am also wondering if it would be possible to leave my <tbody> on the razor page, and just load the ajax data directly into there? Since I already have it generated/ working.

This question has an accepted answers - jump to answer

Answers

  • colincolin Posts: 15,142Questions: 1Answers: 2,586

    Hi @burgoyne ,

    This section of the FAQ should help, it discusses various techniques to improve performance,

    Cheers,

    Colin

  • burgoyneburgoyne Posts: 7Questions: 3Answers: 0

    Thanks @colin

    I've seen that, and attempted the orderClasses option but it unfortunately didn't speed up for me. Which is why I am now trying to load data via ajax to attempt the deferRender option.

    I just am not sure how to proceed with loading data via ajax.

  • awelchawelch Posts: 38Questions: 1Answers: 3
    edited March 2019 Answer ✓

    DataTables is expecting the returned json object to be in the form:

    { data: […<your data here>…]}
    

    you are returning

    { post: […<your data here>…]}
    

    You should get some data showing up if you instantiate your JsonResult like:

    var json = new JsonResult(new { data = postingVMs });
    

    You probably won't even need deferRender, going from loading the table from the DOM to ajax sourced you should see a huge increase in performance.

  • burgoyneburgoyne Posts: 7Questions: 3Answers: 0

    Thank you @awelch
    Would my return statement still return View? Like: return View("Postings", json);

  • awelchawelch Posts: 38Questions: 1Answers: 3

    I don't believe so. I am not terribly familiar with MVC but from what I understand returning View() will try to return a file. What you likely want is Json(). All together it might look like this:

    var postingVMs = (await _adminServices.GetAllPostings()).ToViewModels().ToArray();
     
    return Json(new { data = postingVMs }, JsonRequestBehavior.AllowGet);
    
This discussion has been closed.