如何在jQuery DataTable的AJAX调用上传递额外的参数

时间:2016-10-04 11:38:55

标签: javascript jquery asp.net-mvc datatable datatables

我使用DataTable Documentation上指示的以下代码传递参数。


查看:

$('#example').dataTable( {
      "ajax": {
           "url": "/Student/GetStudents",
           "data": function ( d ) {
               d.test= "some data";
           }
      }
});

控制器:

public ActionResult GetStudents(JQueryDataTableParamModel param, string test)
{
    //code omitted for brevity

    return Json(new
    {
        sEcho = param.sEcho,
        iTotalRecords = allRecords.Count(),
        iTotalDisplayRecords = filteredRecords.Count(),
        aaData = result
    },
    JsonRequestBehavior.AllowGet);
}

虽然"测试"参数传递给Controller," param"参数为null或0,导致datatable返回null数据。另一方面,如果我在datatable参数中使用以下行而不是AJAX调用,则param的所有值都会正确传递给Controller(但是使用AJAX调用并且此行也会导致错误)。我需要将额外的参数传递给Controller并且必须使用AJAX调用。如何在传递参数值时传递它?

"ajaxSource": "/Student/GetStudents",

4 个答案:

答案 0 :(得分:3)

您的javascript代码:

$('#example').dataTable( {
      "ajax": {
           "url": "/Student/GetStudents",
            type: 'GET',
            data: {
                    test1: "This test1 data ",
                    test2: "This test2 data"
                }
        }
});


public ActionResult GetStudents(JQueryDataTableParamModel param, string test)
{
    //code omitted for brevity

     //printing in params in controller with asp.net code. 
     print_r("Data from" ,param.test1 ,param.test2);

    return Json(new
    {
        sEcho = param.sEcho,
        iTotalRecords = allRecords.Count(),
        iTotalDisplayRecords = filteredRecords.Count(),
        aaData = result
    },
    JsonRequestBehavior.AllowGet);
}

答案 1 :(得分:2)

最后,我使用 fnServerData方法解决了这个问题,如下所示。

"ajaxSource": "/Student/GetStudents",

//fnServerData used to inject the parameters into the AJAX call sent to the server-side
"fnServerData": function (sSource, aoData, fnCallback) {
    aoData.push({ "name": "test", "value": "some data" });
    $.getJSON(sSource, aoData, function (json) {
        fnCallback(json)
    });
},

...

无论如何,非常感谢有用的答案。投票+有用的......

答案 2 :(得分:1)

var finalArray = [];
var data = {'test':"some data","test1":"some data1"};
finalArray.push(data);
var rec = JSON.stringify(finalArray);

$('#example').dataTable( {
"ajax": {
   "url": "/Student/GetStudents",
   "data": rec
}
});

public ActionResult GetStudents(JQueryDataTableParamModel param,string test)
{
//code omitted for brevity

 //printing in params in controller with asp.net code. 
 print_r(json_decode(param));

return Json(new
{
    sEcho = param.sEcho,
    iTotalRecords = allRecords.Count(),
    iTotalDisplayRecords = filteredRecords.Count(),
    aaData = result
},
JsonRequestBehavior.AllowGet);
}

答案 3 :(得分:0)

您可以创建一个json数据字符串,您可以在其中传递额外的参数。

var data = {'test':"some data","test1":"some data1"};
    $('#example').dataTable( {
    "ajax": {
       "url": "/Student/GetStudents",
       "data": data
    }
});