Как передать дополнительные параметры в Jquery Datatable Ajax Call

У меня есть Jquery Datatable с действиями на стороне сервера. Здесь мне нужна дата между поиском столбца даты и времени. Я хотел бы передать значения полей ввода FromDate и ToDate к методу вызова jquery datatable ajax..

Вот что я сделал до сих пор:

Поля ввода:

<table class="table table-bordered table-condensed" border="0" cellspacing="5" cellpadding="5">
       <tbody>
           <tr>
               <td>From Date: <input type="text" id="fromDate" name="fromDate" value=""></td>
               <td>To Date: <input type="text" id="toDate" name="toDate"></td>
           </tr>
     </tbody>
</table>

Код JQuery с данными:

    <script>
            $(document).ready(function () {

                // Setup - add a text input to each header cell

                $('#myTable thead tr:eq(0) th:not(:last)').each(function () {
                    var title = $(this).text();
                    $(this).html('<input type="text" placeholder="Search ' + title + '" />');
                });

                var table = $('#myTable').DataTable({
                    //"scrollY": "300px",
                    "scrollX": true,
                    "fixedColumns": {
                        leftColumns: 1,
                        rightColumns: 1
                    },
                    "AutoWidth": false,
                    "processing": true, // for show progress bar
                    "serverSide": true,
                    "aLengthMenu": [[2, 5, 6, -1], [2, 5, 6, "All"]],
                    "iDisplayLength": 2,


                    "ajax": {
                        "url": "/Payment/DueCollectioListLoad",
                        "type": "POST",
                        "datatype": "json",

                      //this is what i have done to pass the input fields values

                        "data": { fromDate: $("#fromDate").val(), toDate: $("#toDate").val()}
                    },
                    "columns": [

                        //here is other column fields

                    ]
                });

                //// Apply the search

                $(table.table().container()).on('focusout', 'thead input', function () {
                    table.column($(this).parent().index() + ':visible')
                        .search(this.value)
                        .draw();
                });

                $('#maxValue').on('focusout', function () {
                    table.draw();
                });


            });


        </script>

Вот метод действия контроллера:

public ActionResult DueCollectioListLoad(string fromDate, string toDate)
{
     //Here is necessary code
}

Все в порядке, но, к сожалению, значения параметров fromDate и toDate всегда становятся нулевыми. Помогите, пожалуйста!


person TanvirArjel    schedule 31.07.2017    source источник
comment
не могу найти minValue и maxValue в вашем html. Может быть, это должно было быть "data": { fromValue: $("#fromDate").val(), toValue : $("#toDate").val(}   -  person Carsten Løvbo Andersen    schedule 31.07.2017
comment
Проверьте это сейчас, пожалуйста! Забыл правильно изменить все места.. Да! вы правы, но это тоже не работает. Значения параметров всегда равны нулю.   -  person TanvirArjel    schedule 31.07.2017
comment
перед var table попробуйте запустить console.log("date is : " + $("#fromDate").val()) и сообщите мне, получили ли вы правильное значение   -  person Carsten Løvbo Andersen    schedule 31.07.2017
comment
Извиняюсь! Правильное получение значения... поскольку дата: 25   -  person TanvirArjel    schedule 31.07.2017
comment
Попробуйте datatables.net/forums/discussion/27216/   -  person Rohan Kumar    schedule 31.07.2017
comment
Недавно я написал об этом сообщение, которое, я думаю, поможет увидеть: codeproject.com/Articles/1170086/   -  person Ehsan Sajjad    schedule 31.07.2017


Ответы (1)


DataTable объект param должен быть следующим:

public class DataTableParams
{
    public int Draw { get; set; }
    public int Start { get; set; }
    public int Length { get; set; }
    public ColumnRequestItem[] Columns { get; set; }
    public OrderRequestItem[] Order { get; set; }
    public SearchRequestItem Search { get; set; }

    // here are the two additional properties

    public string FromDate { get; set; } 
    public string ToDate { get; set; }
}

public class ColumnRequestItem
{
    public string Data { get; set; }
    public string Name { get; set; }
    public bool Searchable { get; set; }
    public bool Orderable { get; set; }
    public SearchRequestItem Search { get; set; }
}

public class OrderRequestItem
{
    public int Column { get; set; }
    public string Dir { get; set; }
}

public class SearchRequestItem
{
    public string Value { get; set; }
    public bool Regex { get; set; }
}

Затем в таблице данных ajax:

"ajax":{
     ................
     'contentType': 'application/json',
     'data': function(d) {
       d.FromDate = $("#fromDate").val(),
       d.ToDate = $("#toDate").val()

       return JSON.stringify(d);
    }
    ............
},

Теперь в методе контроллера:

public ActionResult DueCollectioListLoad([FromBody] DataTableParams dataTableParams)
{
     //Here is necessary code
}
person TanvirArjel    schedule 02.02.2019