Фильтры сбрасываются при нажатии на страницу 2 или не удается применить фильтры на странице 2

#c# #html #jquery #asp.net #asp.net-mvc

#c# #HTML #jquery #asp.net #asp.net-mvc

Вопрос:

Я создал страницу, где я использую разбивку на страницы. Проблема в том, когда я применяю фильтр. Он применяется только к первой странице; когда я нажимаю на вторую страницу, фильтр сбрасывается. Если я применяю фильтр на второй странице, он возвращает меня на первую страницу.

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

 <nav aria-label="DemandPaging">
    @await this.Component.InvokeAsync("Pager", new { pagingList = this.Model.Esas })
</nav>

<nav aria-label="Paging">
    <vc:pager paging-list="@Model" />
</nav>
<form asp-controller="Esa" asp-action="Index" method="post">
    <div>
        @Html.Label("Filter By:")
        @Html.DropDownListFor(model => model.SelectedStatus,
       new SelectList(Enum.GetValues(typeof(Status))),
       "")
        <input type="submit" value="Enter" />
    </div>
    <div class="table-responsive">
        <table class="table">
            <thead>
                <tr>
                    <th>
                        @Html.DisplayNameFor(model => model.EsaProjectId)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.EsaProjectName)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.EmpName)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.Designation)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.StartDate)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.EndDate)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.Billability)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.Location)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.Allocation)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.NblReason)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.Comments)
                    </th>
                    <th>  @Html.DisplayNameFor(model => model.Status)</th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
                @foreach (var item in Model.Esas)
                {
                    <tr>
                        <td>
                            @Html.DisplayFor(modelItem => item.EsaProjectId)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.EsaProjectName)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.EmpName)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.Designation)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.StartDate)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.EndDate)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.Billability)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.Location)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.Allocation)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.NblReason)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.Comments)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.Status)
                        </td>
                        <td>
                            @*<a asp-action="Edit" asp-route-id="@item.CtsEmpId">Edit</a> |
                                <a asp-action="Details" asp-route-id="@item.CtsEmpId">Details</a> |
                                <a asp-action="Delete" asp-route-id="@item.CtsEmpId">Delete</a>*@
                        </td>
                    </tr>
                }
            </tbody>
        </table>
    </div>
</form>
  

Контроллер выглядит следующим образом:

   public async Task<IActionResult> Index(EsaViewModel viewModel, int page = 1)
    {
        int pageSize = 8;
        var query = _context.Esas.AsNoTracking()
                 .OrderBy(s => s.EsaProjectId);
        Status result = viewModel.SelectedStatus;
        if (User.IsInRole("Admin") || User.IsInRole("PMOUser"))
        {
            if (viewModel.SelectedStatus.ToString() == "")
            {
                query = from x in _context.Esas
                        orderby x.Status descending
                        select x;
            }
            else
            {
                query = _context.Esas.AsNoTracking()
                         .Where(s => s.Status == viewModel.SelectedStatus.ToString())
                         .OrderBy(s => s.Status);
            }

        }

        viewModel.Esas = await PagingList.CreateAsync(query, pageSize, page);
        return View(viewModel);
  

Может ли кто-нибудь помочь мне с этим? Как мне сохранить фильтр?

Комментарии:

1. Вы уже пробовали использовать cookies ? Можно попытаться сохранить фильтры в файле cookie, а затем получить эти данные на следующей странице. Также можно попытаться поместить фильтры в URL, а затем передать переменные URL на следующую страницу.

Ответ №1:

В вашем случае примените фильтр на второй странице, он вернет вас на первую страницу.

У меня есть подозрение, что при отправке фильтра параметр страницы равен нулю -> страница равна 1

Так что, я полагаю, вы размещаете скрытое поле в своей форме, чтобы место сохраняло текущую страницу

(viewContext.HttpContext.Request.Строка запроса[«страница»]: имя параметра get — это страница в вашем URL. Пример: http://localhost/?page=2 )

—> он отправит на контроллер и сделает параметр страницы ненулевым.

 <form asp-controller="Esa" asp-action="Index" method="post">
    <div>
        //Get value page in your url
        @Html.Hidden("page", ViewContext.HttpContext.Request.QueryString["page"])
        @Html.Label("Filter By:")
        @Html.DropDownListFor(model => model.SelectedStatus,
       new SelectList(Enum.GetValues(typeof(Status))),
       "")
        <input type="submit" value="Enter" />
    </div>
    <div class="table-responsive">
        <table class="table">
            <thead>
                <tr>
                    <th>
                        @Html.DisplayNameFor(model => model.EsaProjectId)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.EsaProjectName)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.EmpName)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.Designation)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.StartDate)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.EndDate)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.Billability)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.Location)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.Allocation)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.NblReason)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.Comments)
                    </th>
                    <th>  @Html.DisplayNameFor(model => model.Status)</th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
                @foreach (var item in Model.Esas)
                {
                    <tr>
                        <td>
                            @Html.DisplayFor(modelItem => item.EsaProjectId)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.EsaProjectName)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.EmpName)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.Designation)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.StartDate)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.EndDate)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.Billability)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.Location)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.Allocation)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.NblReason)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.Comments)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.Status)
                        </td>
                        <td>
                            @*<a asp-action="Edit" asp-route-id="@item.CtsEmpId">Edit</a> |
                                <a asp-action="Details" asp-route-id="@item.CtsEmpId">Details</a> |
                                <a asp-action="Delete" asp-route-id="@item.CtsEmpId">Delete</a>*@
                        </td>
                    </tr>
                }
            </tbody>
        </table>
    </div>
</form>