jQuery datatable使用ajax POST方法发送自定义对象

时间:2016-10-28 17:04:06

标签: c# asp.net-mvc asp.net-mvc-4 datatables

我想使用jquery datatables默认参数将自定义对象发送到我的控制器方法,以便进行分页,排序,搜索和#记录绑定。

问题是: 当我使用数据表ajax将对象发布到服务器时,它成功发布了我的对象,并且还发送了长度参数,启动和绘制但是停止发送用于排序n搜索的参数。 当我做GET请求时,它会发送所有参数,但不仅是我的自定义对象,显然它不应该

我想发送带有数据表默认参数的自定义对象,用于分页和排序 什么是解决方案?

这是代码:

 $('#example').DataTable({
        "processing": true,
        "serverSide": true,
        "ajax": {
            "url": "/Color/Fetch",
            "type": 'Post',
            // "dataType": "json"
            data: { color: $scope.colorSearch }
            //  dataSrc: 'data'
        },
        "columns": [
            { "data": "Active" },
            { "data": "Company_Id" },
            { "data": "Id" },
            { "data": "IsActive" },
            { "data": "Name" }
        ]
    });

控制器操作:

 public JsonResult Fetch(Color color, int draw, int start, int length)
    {


        string search = Request.QueryString["search[value]"];
        int sortColumn = -1;
        string sortDirection = "asc";
        if (length == -1)
        {
            length = 90;
        }

        // note: we only sort one column at a time
        if (Request.QueryString["order[0][column]"] != null)
        {
            sortColumn = int.Parse(Request.QueryString["order[0][column]"]);
        }
        if (Request.QueryString["order[0][dir]"] != null)
        {
            sortDirection = Request.QueryString["order[0][dir]"];
        }}

1 个答案:

答案 0 :(得分:1)

尝试使用以下方法:

$('#example').DataTable({
    "processing": true,
    "serverSide": true,
    /*
    "ajax": {
        "url": "/Color/Fetch",
        "type": 'Post',
        // "dataType": "json"
        data: { color: $scope.colorSearch }
        //  dataSrc: 'data'
    },
    */      

    "ajaxSource": "/Color/Fetch",
    //fnServerData method used to inject the parameters into the AJAX call sent to the server-side
    "fnServerData": function (sSource, aoData, fnCallback) {
        aoData.push({ "name": "color", "value": "Blue" }); // Add some extra data to the sender
        $.getJSON(sSource, aoData, function (json) {
            /* Do whatever additional processing you want on the callback, then tell DataTables */
            fnCallback(json);
        });
    },

    "columns": [
        { "data": "Active" },
        { "data": "Company_Id" },
        { "data": "Id" },
        { "data": "IsActive" },
        { "data": "Name" }
    ]
});

希望这会有所帮助......