Using a PagedList with a ViewModel ASP.Net MVC

后端 未结 5 2027
暖寄归人
暖寄归人 2020-11-29 01:09

I\'m trying to using a PagedList in my ASP.Net application and I found this example on the Microsoft website http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-m

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-29 01:55

    I figured out how to do this. I was building an application very similar to the example/tutorial you discussed in your original question.

    Here's a snippet of the code that worked for me:

            int pageSize = 4;
            int pageNumber = (page ?? 1);
            //Used the following two formulas so that it doesn't round down on the returned integer
            decimal totalPages = ((decimal)(viewModel.Teachers.Count() /(decimal) pageSize));     
            ViewBag.TotalPages = Math.Ceiling(totalPages);  
            //These next two functions could maybe be reduced to one function....would require some testing and building
            viewModel.Teachers = viewModel.Teachers.ToPagedList(pageNumber, pageSize);
            ViewBag.OnePageofTeachers = viewModel.Teachers;
            ViewBag.PageNumber = pageNumber;
    
            return View(viewModel);
    

    I added

    using.PagedList;
    

    to my controller as the tutorial states.

    Now in my view my using statements etc at the top, NOTE i didnt change my using model statement.

    @model CSHM.ViewModels.TeacherIndexData
    @using PagedList;
    @using PagedList.Mvc;
    
    

    and then at the bottom to build my paged list I used the following and it seems to work. I haven't yet built in the functionality for current sort, showing related data, filters, etc but i dont think it will be that difficult.

    Page @ViewBag.PageNumber of @ViewBag.TotalPages
    
    @Html.PagedListPager((IPagedList)ViewBag.OnePageofTeachers, page => Url.Action("Index", new { page }))
    

    Hope that works for you. Let me know if it works!!

提交回复
热议问题