How to I apply filter while paginating in Asp.net MVC and entity Framework?

前端 未结 3 790
傲寒
傲寒 2020-11-28 16:01

I have a web app that is written using ASP.NET MVC framework. In my Homecontroller I have an action called Index which responds to a Get

3条回答
  •  没有蜡笔的小新
    2020-11-28 16:34

    I think a better way should be passing back to the view the filters in ViewBag. You can make something like below:

    @Html.PagedListPager(
    Model.Tasks, id => 
    Url.Action("Index", new { id, 
    Status = ViewBag.Status , AnotherFilterValue = ViewBag.AnotherFilterValue, ...  }))
    

    But keep in mind to test ViewBag.Status for null value. If it does have a value put it in the route parameter list else set a default ActionLink.

    Then inside the POST action you expect a nullable int like below:

    public ActionResult Index(int? id, int? status, ...)
    {
        int pageNumber = (id ?? 1);
        if (ModelState.IsValid)
        {
    
        using(var connection = new Context())
        {
            if(status != null)
            {
              ViewBag.Status = status.value;
              model.Tasks = connection.Tasks
                                    .Where(task => task.Status == status.value)
                                    .ToPagedList(pageNumber, 30);
            }
            else
            {
               model.Tasks = connection.Tasks
                                      .ToPagedList(pageNumber, 30);
            }
          }
        }
    
       return View(model);
    }
    

提交回复
热议问题