Home > Enterprise >  ASP NET MVC 6 - How to get Product count for each enum value
ASP NET MVC 6 - How to get Product count for each enum value

Time:04-07

I have developed a Site using asp net mvc 6, I have used enom as categories, now I need to get product count under each enom value,

Here is my enum look like,

namespace ecom.Data
{
    public enum BookCategory
    {
        Action,
        Comedy,
        Drama,
        Others
    }
}

What I want is get products count under this enoms,

See here, Front view without product count

This is my Controller Looks like,

using ecom.Data.Services;

namespace ecom.Controllers;

public class HomeController : Controller
{
    
    private readonly IBooksService _service;
    
    public async Task <IActionResult> BookView(string slug)
    {
        
        var data = await _service.GetBookBySlugAsync(slug);

        if(data == null) return View("NotFound");
        return View("BookView", data);
    }

This is model which i use as product model,

namespace ecom.Models
{
    public class Book:IEntityBase
    {
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
        public string Slug { get; set; }
        public string Description { get; set; }
        public double Price { get; set; }
        public string Image { get; set; }
        public string PublishDate { get; set; }
        //enom
        public BookCategory BookCategory { get; set; }
        //Relationships
        public List<Writter_Book> Writter_Books { get; set; }
        //Publisher
        public int PublisherId { get; set; }
        [ForeignKey("PublisherId")]
        public Publisher Publisher { get; set; }

    }
}

My cshtml view right now,

@foreach (var cat in Html.GetEnumSelectList<BookCategory>())
{
    <li><a href="#">@cat.Text <span>()</span></a></li>
}

I want to get product count to above inside foreach's span tag, Anyone can help me with that??

CodePudding user response:

You can use GroupBy and Count to achieve your goal.

Something like

myBooksDataSource
    .GroupBy(book => book.BookCategory)
    .Select(group => new { Category = group.Key, Count = group.Count() });

Which will output a collection of (BookCategory, Count).

{ BookCategory.Action, 20 }
{ BookCategory.Comedy, 204 }

You can create a class to hold that data if you need to pass it around.

public class BookCategoryCountData
{
    public BookCategory Category { get; set; }
    public int Count { get; set; }
}

and select using that object.

public IEnumerable<BookCategoryCountData> GetBookCountByCategory()
{             
     return _context.Books
         .GroupBy(book => book.BookCategory)                 
         .Select(group => new BookCategoryCountData() { 
             Category = group.Key, 
             Count = group.Count() 
         });
 }
  • Related