Datatable jquery Html .BeginForm поиск, возвращающий json вместо таблицы - PullRequest
0 голосов
/ 25 февраля 2020

У меня есть дата jquery, работающая нормально в конфигурациях по умолчанию. Сейчас я пытаюсь выполнить поиск, используя Html.BeginForm, но вместо таблицы возвращаем данные json.

HTML

<table id="Table" class="table table-head-fixed">
    <thead>
        <tr>
            <th>
                Id
            </th>
            <th>
                Name
            </th>
        </tr>
    </thead>
</table>

Datatable JS

@* === LOADER TABLE === *@
<script>
    var gerarTabela;
    var idPes;

    $(document).ready(function () {
            gerarTable = $("#Table").DataTable({
                    //"select": true,
                "processing": true,
                "serverSide": false,
                    "ordering": false,
                    "paging": true,
                    "searching": true,
                    "retrieve": true,
                    "ajax": {
                        "url": '@Url.Action("AjaxHandler", "People")',
                        "type": "POST",
                        "cache": true,
                        "dataType": "json",
                        "error": function () {
                            console.log("error!");
                        },
                        "complete": function () {
                            console.log("complete-> ");
                        }
                },
                "scroller": {
                    loadingIndicator: true
                },
                    "columns": [
                        { "data": "id" },
                        { "data": "name" },
                     },
                ],
                });

   });
</script>

КОНТРОЛЛЕР

    [HttpPost]
    public JsonResult AjaxHandler(string filter)
    {
        List<People> listPeoples = null;

        if (!string.IsNullOrEmpty(filter)) //---ERROR HERE---
        {
            var _Context = _context.People
                .Where(p => p.Name.Contains(filter))
                .Take(20);

            listPeoples = _Context.OrderByDescending(o => o.DtRegister).ToList();

            var ResultObj = new
            {
                Data = listPeoples ,
                Draw = "1",
            };
            return Json(ResultObj );
        }
        else //--THIS WORK FINE--
        {
            var _Context2 = _context.Peoples
                .Take(100);

            listPeoples = _Context2.OrderByDescending(o => o.DtRegister)
                .ToList();

            var ResultObj = new
            {
                Data = listPeoples ,
                Draw = "1",
            };
            return Json(ResultObj);
        }
    }

Это выше отлично работает по умолчанию, но когда я использую Html .BeginForm ниже для поиска, возврат показать только json данные .

<div class="card-tools">
    <div class="input-group" style="width: 250px;">

        @using (Html.BeginForm("AjaxHandler", "People", FormMethod.Post))
        {
            <p>
                <div class="input-group">
                    @Html.TextBox("filter", null, new { @class = "form-control", placeholder = "Searching for?..." })
                    <button type="submit" class="btn btn-default"><i class="fas fa-search"></i></button>
                </div>
            </p>
        }
    </div>
</div>

enter image description here

enter image description here

enter image description here

1 Ответ

1 голос
/ 25 февраля 2020

Вам нужно вызвать событие, отправленное формой в jQuery, и использовать ajax для повторной привязки и загрузки DataTable через URL-адрес и параметр фильтра для повторной визуализации этой таблицы.

<script>
   var gerarTabela;
   var idPes;

    $(document).ready(function () {
        gerarTable = $("#Table").DataTable({
            //"select": true,
            "processing": true,
            "serverSide": false,
            "ordering": false,
            "paging": true,
            "searching": true,
            "retrieve": true,
            "ajax": {
                 "url": '@Url.Action("AjaxHandler", "People")',
                "type": "POST",
                "cache": true,
                "dataType": "json",
                "error": function () {
                    console.log("error!");
                },
                "complete": function () {
                    console.log("complete-> ");
                }
            },
            "scroller": {
                loadingIndicator: true
            },
            "columns": [
                { "data": "id" },
                { "data": "name" },]
        });

        ***//add this event***
        $('form').on("submit", function (event) {
            event.preventDefault();
             gerarTable.ajax.url($(this).attr('action')+"?filter="+$("#filter").val()).load();

        });

    });

</script>

Вот результат:

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...