I'm trying to select products from a certain category but apparently it doesn't work that way. I am applying the code from below. Мy goal is to filter only the products of a certain category from a dropdown menu.
public class SingleCategoryViewModel : IMapFrom<Data.Models.Category>
{
public int Id { get; set; }
[Required]
[MinLength(3)]
public string Name { get; set; }
}
public class ListCategoryViewModel
{
public IEnumerable<SingleCategoryViewModel> Categories { get; set; }
}
//Controller
public IActionResult ByName(int categoryId)
{
var viewModel = new ProductListViewModel()
{
Products = this._productService.GetByCategoryId<ProductInListViewModel>(categoryId),
};
return this.View(viewModel);
}
//Service
public IEnumerable<T> GetByCategoryId<T>(int categoryId)
{
var query = this.productRepository.All()
.Where(x => x.CategoryId == categoryId)
.To<T>().ToList();
return query;
}
@using AspNetCoreTemplate.Web.ViewModels.Category;
@model ListCategoryViewModel
<select>
@foreach (var item in Model.Categories)
{
<option><a asp-controller="Products" asp-action="ByName" asp-route- categoryId="@item.Id">@item.Name</a></option>
}
</select>