PagedListResult未在第二页上包含搜索过滤器

时间:2014-11-16 14:07:01

标签: c# asp.net pagedlist

我有问题。当我在表单中搜索数据并且表单返回结果时,我想继续第二页但是Html.PagedListPager返回所有数据的第二页,而不是搜索到的数据。

控制器:

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>

脚本:

$(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 个答案:

答案 0 :(得分:0)

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

您指定page = 1然后它将始终显示第一页数据

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);

}