AJAX Post object AND retrieve data for data table

AJAX Post object AND retrieve data for data table

KKingMCGKKingMCG Posts: 2Questions: 1Answers: 0

I have used DataTables to post to a C# method and retrieve data for datatables (without sending any data to the method). What I'm interested in doing now is posting parameters in the form of an object to my C# controller and getting the data back. I'm having some trouble in finding examples of this.

$("#SearchResultsTable").DataTable({
    "deferRender": true,
    "ajax": {
        type: "POST",
        url: "/Home/MyMethod",
        contentType: "application/json; charset=utf-8",
        data: function(d) { return JSON.stringify(d); }
    }
});

The above works.

Answers

  • KKingMCGKKingMCG Posts: 2Questions: 1Answers: 0

    What I can't seem to find is where I could send an object in that post, i.e.

    var formData = {
        MyFilter: '@Model.MyFilter',
        DocumentID: '@Model.DocumentID',
        DocumentName: '@Model.DocumentName'
    }
    
    and then in the method, I would get the post data as such:
    [HttpPost]
    public JsonResult MyMethod(SearchResults model)
    {
         var result = dataClient.GetSearchResults(model);
    
         return Json(new { data = result.Select(a => new List<string> {
             a.DocumentID.ToString(),
             a.DocumentName,
             a.DocumentType
         })
    });
    }
    

    How does this work? If I send formData in the data ajax call, how do I then get my results back from the controller?

  • allanallan Posts: 62,316Questions: 1Answers: 10,226 Site admin

    Use ajax.data to submit data to the server-side. This example does that (it uses server-side processing as well, but you don't need that for ajax.data to work).

    Allan

Sign In or Register to comment.