I am working on an e-commerce website using ASP.NET MVC 5, EF6 and LINQ. I have a Products table in my database. In my UI, I have multiple parameters for the filtering of my products:
- checkboxes for different categories
- minimum and maximum prices
- checkboxes for different colors
And I have written this action method:
[HttpPost]
public PartialViewResult FilterProducts(int[] categoriesIds, decimal minPrice, decimal? maxPrice, string[] colors)
{
if (categoriesIds == null)
{
var randomProducts = db.Products
.OrderBy(p => Guid.NewGuid());
return PartialView("_LoadProducts", randomProducts.ToList());
}
else
{
var filteredProducts = db.Products
.Where(p => categoriesIds.Contains(p.CategoryId)
&& (p.DiscountedPrice >= minPrice
&& p.DiscountedPrice <= maxPrice || maxPrice == null));
if (colors != null)
{
filteredProducts = filteredProducts
.Where(p => colors.Contains(p.Color));
}
return PartialView("_LoadProducts", filteredProducts.ToList());
}
}
This works fine. But I'm confused to whether this can be improved? It includes a lot of if/else statements just to filter products. Is there any problem with my design overall? Are there any best practices? Any help will be highly appreciated. Thanks.