0

I have a list of products in a table on db. I got them on a single page with this code:

public ActionResult Index() {
    var products = productsRepository.GetAll();
    IEnumerable<Models.Product> productsView = products.Select(p => new Models.Product() {
        Id = p.Id,
        Category = p.Category.Name,
        Brand = p.Brand,
        Name = p.Name,
        Type = p.Type,
        IsActive = p.IsActive,
        SellPrice = p.SellPrice,
        AddedDate = p.AddedDate
    });
    return View(productsView);
}

How should i get 'n' products per page and have multiple pages ? Ty

kiyah
  • 1,502
  • 2
  • 18
  • 27
  • What you're looking for is `pagination`. Here's an older Stack overflow post which explains how to do it. https://stackoverflow.com/questions/446196/how-do-i-do-pagination-in-asp-net-mvc – Sudheesh Singanamalla Jan 28 '18 at 13:34

2 Answers2

0

Solve it . I changed to a ienumerable and i had an error on the redirect page but all works well now. Thank u EDIT: At the very start my index with paginating was looking like this

    public ActionResult Index(int page = 0)
    {

        var products = productsRepository.GetAll();



        const int PageSize = 5; // you can always do something more elegant to set this

        var count = productsView.Count();

        var data = products.OrderBy(o=>o.Brand).Skip(page * PageSize).Take(PageSize).ToList();

        this.ViewBag.MaxPage = (count / PageSize) - (count % PageSize == 0 ? 1 : 0);

        this.ViewBag.Page = page;

        return this.View(data);
    }

My view was expecting something of type i enumerable so after i added this everything was fine.

IEnumerable<Models.Product> productsView = products.Select(p => new Models.Product()
        {
            Id = p.Id,
            Category = p.Category.Name,
            Brand = p.Brand,
            Name = p.Name,
            Type = p.Type,
            IsActive = p.IsActive,
            SellPrice = p.SellPrice,
            AddedDate = p.AddedDate

        });

I m a begginer so im struggling a lot with these kind of things

  • You changed what to `IEnumerable`? You should post what you've fixed, so that future readers can benefit if they have a similar issue. – Blue Jan 29 '18 at 13:27
0

You're using different types, in one place you're using BarHelper.Domain.Product and another BarHelper.Areas.Admin.Models.Product. So, make sure you're passing the same type.

Tiago Ávila
  • 2,737
  • 1
  • 31
  • 34