PagedListResult not included search filter on second page

206 Views Asked by At

I have a problem. When I am searching data in my form and when the form returns result then I want to go on second page but then Html.PagedListPager returns second page for all data, not for searched data.

controller:

public ActionResult List(string name = null, int page = 1)
{
        var model =
        repository.GetMeals()
        .Where(r => name == null || r.Name.StartsWith(name))
        .Select(r => new Meal
        {
           Id = r.Id,
           Name = r.Name,
           Protein = r.Protein,
           Carbohydrates = r.Carbohydrates,
           Fat = r.Fat,
           Calories = r.Calories
        }).ToPagedList(page, 50);

        if(Request.IsAjaxRequest())
        {
            return PartialView("_Meals", model);
        }
        return View(model);
}

list.cshtml:

<div class="col-md-6 col-md-offset-4">
    <form method="get" action="@Url.Action("List")" class="form-inline">
        <input type="search" class="form-control" id="searchInput">
        <button type="submit" class="btn btn-info" id="searchButton">Szukaj po nazwie</button>
    </form>
</div>
@Html.Partial("_Meals", Model);

_meals.cshtml:

<div id="meals">
    <div class="pagedList col-md-6 col-md-offset-4 ">
        @Html.PagedListPager(Model, page => Url.Action("List", new { page }),
            PagedListRenderOptions.MinimalWithItemCountText)
    </div>
  // somethings...
</div>

scripts:

$(document).on("click", ".pagedList a", function () {
var $a = $(this);
$.ajax({
    url: $a.attr("href"),
    data: $("#searchInput").val(),
    type: 'GET'
})
.done(function (data) {
    $("#meals").replaceWith(data);
});
return false;
});

$(document).on("click", "#searchButton", function () {
var $a = $("#searchInput").val();
$.ajax({
    type: 'GET',
    url: '/Meal/List',
    data: { name: $a }
})
.done(function (data) {
    $("#meals").replaceWith(data);
});
return false;
});
1

There are 1 best solutions below

1
On
public ActionResult List(string name = null, int page = 1)

you are assign page=1 then it will always show page one data

usethis

 public ActionResult List(string name, int? page)
 {
 int pageNumber = (page ?? 1);
 var model =
    repository.GetMeals()
    .Where(r => name == null || r.Name.StartsWith(name))
    .Select(r => new Meal
    {
       Id = r.Id,
       Name = r.Name,
       Protein = r.Protein,
       Carbohydrates = r.Carbohydrates,
       Fat = r.Fat,
       Calories = r.Calories
    }).ToPagedList(pageNumber , 50);

    if(Request.IsAjaxRequest())
    {
        return PartialView("_Meals", model);
    }
    return View(model);

}