Please do not mark this as a duplicate because I've already checked these but none of them helped me.
Sequence contains no elements?
Using a PagedList with a ViewModel ASP.Net MVC
I'm trying to use pagedList in my asp.net mvc project but it's giving me "Sequence contains no elements?" when I click on page numbers. First I have 2 Table Products and Images.
Product Contains: ProductID - ProductName - ProductDescription.
Images contains :ImageID - ImagePath - ProductFK
I have a viewModel That contains these 2 tables
public class myViewModel
{
public IPagedList<Products> myProducts { get; set; }
public IPagedList<Images> myImages{ get; set; }
}
In my Search View I have this.
@model PagedList.IPagedList<myViewModel>
@using PagedList;
@using PagedList.Mvc;
<div>
<input type="text" name="search">
<button type="submit">Search</button>
</div>
@foreach (Products item in Model.First().myProducts)
{
@item.ProductName
@item.ProductDescription
}
<div>
// Page Index
@(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount
@Html.PagedListPager(Model.First().myProducts, page => Url.Action("Search", new { page, search = Request.QueryString["search"] }), PagedListRenderOptions.PageNumbersOnly)
And Here's my search method in my home controller
public ActionResult Search(string search, int? page)
{
int pageSize = 3;
int pageNumber = (page ?? 1);
var Items= new[] {
new myViewModel { myProducts = DB.Products.Where(a=>a.ProductName.Contains(search)).OrderByDescending(a=>a.ProductID).ToPagedList(pageNumber,pageSize),
}
};
return View(Items.ToPagedList(pageNumber, pageSize));
}
The search worked great and even the page index is giving me the number of pages depending on my search results(meaning that if I have a product with a name="abc" and I have 9 abc products in my table, if I'm showing 3 element only in each page ,Im getting 1,2,3 for page indexing.)
The only thing the goes wrong is when I click on a page number to navigate to other results, it gives me "Sequence contains no elements". Please if someone can help me, it would be so appreciated .