Reputation: 11
Here is product filtering frontend HTML code:
<div class="widget widget-collapsible">
<h3 class="widget-title">
<a data-toggle="collapse" href="#widget-4" role="button" aria-expanded="true" aria-controls="widget-4">
Brands
</a>
</h3><!-- End .widget-title -->
<div class="collapse show" id="widget-4">
<div class="widget-body">
<div id="brand-filter" name="brand-filter" class="brand-filter">
@foreach (var brand in ViewBag.brandlist as List<Brand>)
{
<div id="brand-filter" class="filter-item">
<div class="custom-control custom-checkbox">
<input type="checkbox"
class="custom-control-input brand-checkbox"
id="@brand.id"
value="@brand.id"
name="custom-control-input">
<label class="custom-control-label" for="@brand.id">
@brand.name
</label>
</div><!-- End .custom-checkbox -->
</div>
<!-- End .filter-item -->
}
</div><!-- End .brand-filter -->
</div><!-- End .widget-body -->
</div><!-- End .collapse -->
</div><!-- End .widget -->
I am fetching brandlist, categories from a SQL database with EF Core.
This is my AJAX code:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
const formatCurrency = (value) => new Intl.NumberFormat('tr-TR', {
minimumFractionDigits: 2,
maximumFractionDigits: 2
}).format(value) + ' TL';
const loadProducts = () => {
// Gather filter values
const category = $('#category-filter').val();
// Collect all checked brand checkboxes
const brands = $('brand-filter input.custom-control-input:checked').map((_, el) => $(el).val()).get();
const sortby = $('#sortby-filter').val();
// Send AJAX request
$.ajax({
url: '/urun/Filter', // Update this with the actual filtering endpoint
method: 'GET',
data: { category, brands: brands.join(','), sortby }, // Send brands as a comma-separated string
success: (data) => {
const productContainer = $('#product-list').empty();
if (data.length) {
data.forEach((product) => {
const addToCartUrl = `@Url.Action("AddToCart", "Home")?productId=${product.id}`;
const loginUrl = '/Login/Index';
productContainer.append(`
<div class="product-item col-6 col-md-4 col-lg-3">
<div class="product product-4">
<figure class="product-media">
<a href="/urun/${product.slug}">
<img src="${product.image}" alt="${product.name}" class="product-image">
</a>
<div class="product-action-vertical">
${product.a == 0 ? `
<a href="${loginUrl}" class="btn-product-icon btn-cart btn-expandable"><span>Sepete Ekle</span></a>
` : `
<a href="${addToCartUrl}" class="btn-product-icon btn-cart btn-expandable"><span>Sepete Ekle</span></a>
`}
</div>
</figure>
<div class="product-body">
<h3 class="product-title">
<a href="/urun/${product.slug}">
<span><a style="color:#015fc9" href="brand.html">${product.brandname}</a></span>
${product.name}
</a>
</h3>
<div class="product-price">
${product.indirimvarmı ? `
<span class="new-price">${formatCurrency(product.indirimliFiyat)}</span>
<span class="old-price">Eski Fiyat: ${formatCurrency(product.price)}</span>
` : `
<div class="price">${formatCurrency(product.price)}</div>
`}
</div>
<div class="product-action">
${product.user == 1 ? `
<a href="${loginUrl}" class="btn-product btn-cart"><span>Sepete Ekle</span></a>
` : `
<a href="${addToCartUrl}" class="btn-product btn-cart"><span>Sepete Ekle</span></a>
`}
</div>
</div>
</div>
</div>
`);
});
} else {
productContainer.append('<p>No products found.</p>');
}
},
error: () => alert('Ürünler yüklenirken bir hata oluştu.')
});
}
// Event bindings
$('#category-filter, #sortby-filter').on('change', loadProducts);
$(document).on('change', '.brand-checkbox', loadProducts);
// Initial load
$(document).ready(loadProducts);
</script>
Categories filter UI HTML markup:
<div class="widget widget-collapsible">
<h3 class="widget-title">
<a data-toggle="collapse" href="#widget-1" role="button" aria-expanded="true" aria-controls="widget-1">
Category
</a>
</h3><!-- End .widget-title -->
<div class="collapse show" id="widget-1">
<div class="widget-body">
<div class="filter-items filter-items-count">
@foreach (var category in ViewBag.categories as List<Category>)
{
<div class="filter-item">
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" id="[email protected]">
<label class="custom-control-label" for="[email protected]">@category.categoryname</label>
</div><!-- End .custom-checkbox -->
</div><!-- End .filter-item -->
}
</div><!-- End .filter-items -->
</div><!-- End .widget-body -->
</div><!-- End .collapse -->
```
Sortby
filter is working perfectly but on brands, categories filters with checkboxes are not working. I think I have issues with checkboxes id's and names. Please help me.
I can code select 1 filter item and runs perfectly but i want to filter with multiple categories and brands.
Upvotes: 1
Views: 49
Reputation: 34908
According to the client-side call, you are passing a single category and attempting to send multiple brands:
data: { category, brands: brands.join(','), sortby }
By attempting a string join
your API endpoint would need to accept "brands" as a string
, not an array/list. You may want to post up your server-side method signature but the Join
is likely unnecessary:
data: { category, brands: brands, sortby }
public IActionResult Filter(int category, [FromQuery(Name = "brands")] int[] brands, string sortby)
GET requests expect arguments over query string, but complex types I believe default to being expected from the request body. The [FromQuery]
may be needed to ensure that. If you select 2 brands (Id #1 & #2) your query string should look like "...&brands=1&brands=2..." Using a comma-delimited string with the Join
should work as well, but you would need to parse the IDs back out server side:
public IActionResult Filter(int category, string brands, string sortby)
{
var brandIds = brands.Split(',', StringSplitOptions.RemoveEmptyEntries)
.Select(x => int.Parse(x))
.ToList();
Assuming the IDs are int
. This would need additional guards/error handling for any eventuality where bad data comes in.
Beyond that, consider revising your question with details about what you see during debugging such as whether the Filter endpoint is being reached or not, or whether expected arguments are missing when it is reached, etc. rather than simply "it's not working". When describing issues it is best to express it in terms of "what did I expect to see" and "what did I actually see".
Upvotes: 0