TransWikia.com

How to call Ajax datatables with parameter ASP.NET MVC?

Stack Overflow Asked by Truong Hoang on February 19, 2021

I want to send parameter when clicking a tag to controller but always null.
How can I get parameters when using datatable ajax? Please help me.

My code in controller:

public JsonResult Getdata(string isvk)
{
        var orders = from o in db.Orders
                     select o;

        if (isvk == null)
        {
            return Json(new { data = orders }, JsonRequestBehavior.AllowGet);
        }

        switch (isvk)
        {
            case "canceled":
                orders = db.Orders.Where(o => o.Status == -1 || o.Status == -2);
                break;

            case "pending":
                orders = db.Orders.Where(o => o.Status == 0);
                break;

            case "approved":
                orders = db.Orders.Where(o => o.Status == 1);
                break;

            case "delivered":
                orders = db.Orders.Where(o => o.Status == 2);
                break;

            default:
                orders = db.Orders;
                break;
        }

        return Json(new { data = orders.ToList() }, JsonRequestBehavior.AllowGet);
}

Tag <a> is outside the table:

<a href="@Url.Action("Index","Cart", new {isvk = "pending" })">peding</a>

My Script:

var datatable = $("#myTable").DataTable({
        ajax: {
            type: "GET",
            url: "@Url.Action("Getdata","Cart")",

    },
    columns: [
        { data: "CodeOrder"},
        { data: "FullName"},
        { data: "Email"},
        { data: "Phone" },
    ]

3 Answers

To send data from DataTables to the server (i.e. to your controller), you use the data option of the ajax function. So, first of all, add that:

ajax: {
  type: "GET",
  url: "@Url.Action("Getdata","Cart")",
  data: function() {
    return dataToSend;
  }
},

You declare dataToSend as an empty JavaScript object at the start of the document.ready function:

var dataToSend = {};

Here is my simplified version of your <a> tag:

<a id="linkOne" linkData="pending" href="#">submit</a>

Following the dataToSend declaration, I added the following click handler for the <a> tag:

$("a#linkOne").on('click', function() {
  event.preventDefault();
  var linkDataValue = $( this ).attr( 'linkData' )
  dataToSend = { "linkData": linkDataValue };
  //console.log( dataToSend );
  table.ajax.reload();
});

This code extracts the "pending" text from linkData="pending" in the <a> tag and adds it to the dataToSend object.

Finally, I trigger the DataTable ajax call using reload().

In the controller, this data will be received as a standard URL query parameter (because you are using GET):

linkData=pending

So you can access that in the usual way and format your response accordingly.

In your case, you need to replace my dataToSend logic with your required logic, for your specific <a> tag.

An important point here is that you need to create your dataToSend object correctly.

For one value, it is created as this, as in the above example:

{ "linkData": "pending" }

If you need to send multiple values (e.g. if you are processing a form) then you would build a JavaScript object like this:

[
  {
    "name": "fieldOne",
    "value": "x"
  },
  {
    "name": "fieldTwo",
    "value": "y"
  }
]

In this case, the object is an array of key-pair values.

For simple forms, the JavaScript serializeArray() function can assist with that - for example:

$( "#formOne" ).on( "submit", function( event ) {
  event.preventDefault();
  dataToSend = $( "#formOne" ).serializeArray();
  //console.log( dataToSend );
  table.ajax.reload();
});

UPDATE

In case it helps, here is the full HTML page for my test code.

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Personnel</title>
  <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
  <script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">
  <link rel="stylesheet" type="text/css" href="https://datatables.net/media/css/site-examples.css">
</head>

<body>

<div style="margin: 20px;">

<table id="example" class="display" style="width:100%">
    <thead>
        <tr>
            <th>ID</th>
            <th>First Name</th>
            <th>Name</th>
            <th>Phone</th>
        </tr>
    </thead>
</table>

<br>
<form id ="formOne">
    <input id="fieldOne" type="text" name="fieldOne"></input>
    <input id="fieldTwo" type="text" name="fieldTwo"></input>
    <input type="submit" value="Submit">
</form>
<br>
<a id="linkOne" linkData="pending" href="#">submit</a>

</div>

<script type="text/javascript">

  $(document).ready(function() {

    var dataToSend = {};

    $( "#formOne" ).on( "submit", function( event ) {
      event.preventDefault();
      dataToSend = $( "#formOne" ).serializeArray();
      //console.log( dataToSend );
      table.ajax.reload();
    });

    $("a#linkOne").on('click', function() {
      event.preventDefault();
      var linkDataValue = $( this ).attr( 'linkData' )
      dataToSend = { linkData: linkDataValue };
      //console.log( dataToSend );
      table.ajax.reload();
    });

    var table = $('#example').DataTable( {
      ajax: {
        url: "http://localhost:7000/personnel",
        method: "POST",
        data: function( ) {
          return dataToSend;
        },
        dataSrc: ''
      },
      "columns": [
        { "data": "id" },
        { "data": "firstname" },
        { "data": "name" },
        { "data": "phone" }
      ]

    } );

  } );

</script>

</body>

</html>

Correct answer by andrewjames on February 19, 2021

Update Script

$(document).ready(function () {
        //test
        var dataToSend = {};
        $("a#linkOne").on('click', function () {
            event.preventDefault();
            var linkDataValue = $(this).data('id')
            var linkurl = $(this).data('url')
            dataToSend = { isvk: linkDataValue };
            datatable.ajax.reload();
        });
        var datatable = $("#myTable").DataTable({
            ajax: {
                type: "GET",
                url: "@Url.Action("Getdata","Cart")",
                data: function () {
                    return dataToSend;
                }
            },
            columns: [
                { data: "CodeOrder" },
                { data: "FullName" },
                { data: "Email" },
                { data: "Phone" },
                
            ],
          
        });
    });

tag <a>:

<a id="linkOne" data-id="pending" href="#">submit</a>

Answered by Truong Hoang on February 19, 2021

Welcome to StackOverflow!

You're already very close and the snippets you provided are helpful. What you're missing is that you want the data to update without leaving the page. Using an anchor tag the way you are will direct you to that page. Also, you controller action is returning a JsonResult, which won't return any type of view (but is correct in this case).

You need to add a page event that triggers on clicking the button and refreshes the data source.

There's a few approaches you can take for this, but here's one of them:

<button class="filter-datatable" data-url="@Url.Action("Index","Cart", new {isvk = "pending" })">
// pageScript.js
// jquery, initialization, etc...

$('.filter-datatable').on('click', function() {
    var newSource = $(this).data('url');
    datatable.ajax.url(newSource).load();
}

Answered by Ben Sampica on February 19, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP