Я пытаюсь выполнить фильтрацию цен с помощью ползунка. Вид будет такой
. Я использую ajax для заполнения цены. Вот код слайдера и представления продукта:
<div class = "price-filter">
<div id = "price-slider"></div>
<div class = "input-number price-min">
<input id = "price-min" type = "number">
<span class = "qty-up">+</span>
<span class = "qty-down">-</span>
</div>
<span>-</span>
<div class = "input-number price-max">
<input id = "price-max" type = "number">
<span class = "qty-up">+</span>
<span class = "qty-down">-</span>
</div>
</div>
//product
<div id = "store" class = "col-md-9">
<div class = "row">
<!-- product -->
@foreach (var item in Model.Take(6))
{
<div class = "col-md-4 col-xs-6">
<div class = "product">
<a href = "/post/@SlugGenerator.SlugGenerator.GenerateSlug(item.ProductName)[email protected]().ProductVariations.FirstOrDefault().ProductVarId" />
<div class = "product-img">
<img src = "~/Contents/img/@item.ProductItems.FirstOrDefault().Image1" width = "200" height = "200" alt = "">
<div class = "product-label">
<span class = "sale">-30%</span>
<span class = "new">NEW</span>
</div>
</div>
<div class = "product-body">
@* <p class = "product-category">@item.Category.CategoryName.ToUpper()</p> *@
<h3 class = "product-name"><a href = "#">@item.ProductName.ToUpper()</a></h3>
<h4 class = "product-price">[email protected]<del class = "product-old-price">@* $@(item.Product.Price + 200) *@</del></h4>
<div class = "product-rating">
<i class = "fa fa-star"></i>
<i class = "fa fa-star"></i>
<i class = "fa fa-star"></i>
<i class = "fa fa-star"></i>
<i class = "fa fa-star"></i>
</div>
<div class = "product-btns">
<button class = "add-to-wishlist"><i class = "fa fa-heart-o"></i><span class = "tooltipp">add to wishlist</span></button>
<button class = "add-to-compare"><i class = "fa fa-exchange"></i><span class = "tooltipp">add to compare</span></button>
<button class = "quick-view"><i class = "fa fa-eye"></i><span class = "tooltipp">quick view</span></button>
</div>
</div>
</div>
</div>
}
<!-- /product -->
</div>
</div>
Код ajax, позволяющий фильтровать товар по цене без перезагрузки страницы:
<script>
$(function () {
$("#price-slider").slider({
range: true,
min: 100000,
max: 2000000,
values: [100000, 2000000],
slide: function (event, ui) {
$("#price-min").val(ui.values[0]);
$("#price-max").val(ui.values[1]);
},
stop: function (event, ui) {
var min = ui.values[0];
var max = ui.values[1];
var cateid = $('#category-id').val();
$.ajax({
url: '@Url.Action("FilterByPrice", "ProductView")',
type: 'GET',
data: { minPrice: min, maxPrice: max, categoryId: cateid },
success: function (productlist) {
var newproductrow = "";
$.each(productlist, function (index, item) {
newproductrow += '<div class = "col-md-4 col-xs-6">';
newproductrow += '<div class = "product">';
newproductrow += '<a href = "/post/' + item.SlugGenerator.SlugGenerator.GenerateSlug(item.ProductName) + '-' + item.ProductItems[0].ProductVariations[0].ProductVarId + '">';
newproductrow += '<div class = "product-img">';
newproductrow += '<img src = "~/Contents/img/' + item.ProductItems[0].Image1 + '" width = "200" height = "200" alt = "">';
newproductrow += '<div class = "product-label">';
newproductrow += '<span class = "sale">-30%</span>';
newproductrow += '<span class = "new">NEW</span>';
newproductrow += '</div>'; // Close product-label
newproductrow += '</div>'; // Close product-img
newproductrow += '<div class = "product-body">';
newproductrow += '<h3 class = "product-name"><a href = "#">' + item.ProductName.toUpperCase() + '</a></h3>';
newproductrow += '<h4 class = "product-price">$' + item.Price + '<del class = "product-old-price">$' + (item.Price + 200) + '</del></h4>';
newproductrow += '<div class = "product-rating">';
newproductrow += '<i class = "fa fa-star"></i>';
newproductrow += '<i class = "fa fa-star"></i>';
newproductrow += '<i class = "fa fa-star"></i>';
newproductrow += '<i class = "fa fa-star"></i>';
newproductrow += '<i class = "fa fa-star"></i>';
newproductrow += '</div>'; // Close product-rating
newproductrow += '<div class = "product-btns">';
newproductrow += '<button class = "add-to-wishlist"><i class = "fa fa-heart-o"></i><span class = "tooltipp">add to wishlist</span></button>';
newproductrow += '<button class = "add-to-compare"><i class = "fa fa-exchange"></i><span class = "tooltipp">add to compare</span></button>';
newproductrow += '<button class = "quick-view"><i class = "fa fa-eye"></i><span class = "tooltipp">quick view</span></button>';
newproductrow += '</div>'; // Close product-btns
newproductrow += '</div>'; // Close product-body
newproductrow += '</div>'; // Close product
newproductrow += '</div>'; // Close col-md-4
});
$("#store .row").html(newproductrow);
}
});
}
});
});
</script>
Контроллер, фильтрующий цену:
[HttpGet]
public IActionResult FilterByPrice(int minPrice, int maxPrice, int categoryId)
{
var filteredProducts = _context.Products
.Where(p => p.Price >= minPrice && p.Price <= maxPrice && p.CategoryId == categoryId)
.ToList();
return new JsonResult(filteredProducts);
}
Но когда я настроился на эту планку, ничего не произошло. Я открываю сеть и выбираю Fetch/XHR, я вижу, что при настройке панели возвращается json img. Возврат JSON:
{
"$id": "1",
"$values": [
{
"$id": "2",
"productId": 8,
"productName": "POSEE",
"categoryId": 4,
"price": 400000,
"description": null,
"brand": 5,
"brandNavigation": null,
"category": null,
"productItems": {
"$id": "3",
"$values": []
}
},
{
"$id": "4",
"productId": 9,
"productName": "ShondoHCM",
"categoryId": 4,
"price": 500000,
"description": null,
"brand": 11,
"brandNavigation": null,
"category": null,
"productItems": {
"$id": "5",
"$values": []
}
},
{
"$id": "6",
"productId": 10,
"productName": "BITIS",
"categoryId": 4,
"price": 800000,
"description": null,
"brand": 4,
"brandNavigation": null,
"category": null,
"productItems": {
"$id": "7",
"$values": []
}
}
]
}
Кто-нибудь знает проблему, почему товар не отображается по цене? Я полагал, что речь идет о цикле for. Я очень ценю любые инструкции. Спасибо



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Скорее всего ошибка связана с тем, что вы используете свойства PascalCase в коде jQuery, а JSON получен в CamelCase. чтобы исправить это, измените свой скрипт на:
<script>
$(function () {
$("#price-slider").slider({
range: true,
min: 100000,
max: 2000000,
values: [100000, 2000000],
slide: function (event, ui) {
$("#price-min").val(ui.values[0]);
$("#price-max").val(ui.values[1]);
},
stop: function (event, ui) {
var min = ui.values[0];
var max = ui.values[1];
var cateid = $('#category-id').val();
$.ajax({
url: '@Url.Action("FilterByPrice", "ProductView")',
type: 'GET',
data: { minPrice: min, maxPrice: max, categoryId: cateid },
success: function (productlist) {
var newproductrow = "";
$.each(productlist, function (index, item) {
newproductrow += '<div class = "col-md-4 col-xs-6">';
newproductrow += '<div class = "product">';
newproductrow += '<a href = "/post/' + item.SlugGenerator.SlugGenerator.GenerateSlug(item.productName) + '-' + item.productItems[0].productVariations[0].productVarId + '">';
newproductrow += '<div class = "product-img">';
newproductrow += '<img src = "~/Contents/img/' + item.productItems[0].image1 + '" width = "200" height = "200" alt = "">';
newproductrow += '<div class = "product-label">';
newproductrow += '<span class = "sale">-30%</span>';
newproductrow += '<span class = "new">NEW</span>';
newproductrow += '</div>'; // Close product-label
newproductrow += '</div>'; // Close product-img
newproductrow += '<div class = "product-body">';
newproductrow += '<h3 class = "product-name"><a href = "#">' + item.productName.toUpperCase() + '</a></h3>';
newproductrow += '<h4 class = "product-price">$' + item.price + '<del class = "product-old-price">$' + (item.price + 200) + '</del></h4>';
newproductrow += '<div class = "product-rating">';
newproductrow += '<i class = "fa fa-star"></i>';
newproductrow += '<i class = "fa fa-star"></i>';
newproductrow += '<i class = "fa fa-star"></i>';
newproductrow += '<i class = "fa fa-star"></i>';
newproductrow += '<i class = "fa fa-star"></i>';
newproductrow += '</div>'; // Close product-rating
newproductrow += '<div class = "product-btns">';
newproductrow += '<button class = "add-to-wishlist"><i class = "fa fa-heart-o"></i><span class = "tooltipp">add to wishlist</span></button>';
newproductrow += '<button class = "add-to-compare"><i class = "fa fa-exchange"></i><span class = "tooltipp">add to compare</span></button>';
newproductrow += '<button class = "quick-view"><i class = "fa fa-eye"></i><span class = "tooltipp">quick view</span></button>';
newproductrow += '</div>'; // Close product-btns
newproductrow += '</div>'; // Close product-body
newproductrow += '</div>'; // Close product
newproductrow += '</div>'; // Close col-md-4
});
$("#store .row").html(newproductrow);
}
});
}
});
});
Также эта строка выдаст ошибку:
newproductrow += '<a href = "/post/' + item.SlugGenerator.SlugGenerator.GenerateSlug(item.productName) + '-' + item.productItems[0].productVariations[0].productVarId + '">';
лучше вызвать SlugGenerator.GenerateSlug в бэкэнде, как показано ниже:
[HttpGet]
общедоступная асинхронная задача FilterByPrice (int minPrice, int maxPrice, int CategoryId) {
var filteredProducts = await _context.Products
.Where(p => p.Price >= minPrice && p.Price <= maxPrice && p.CategoryId == categoryId)
.Select(m => new ProductView
{
Brand = m.Brand,
BrandNavigation = m.BrandNavigation,
Category = m.Category,
CategoryId = categoryId,
Description = m.Description,
Id = m.Id,
Price = m.Price,
ProductId = m.ProductId,
ProductItems = m.ProductItems,
ProductName = m.ProductName,
//Here to generate SlugName using SlugGenerator (Note that method must be static)
SlugName = Item.SlugGenerator.GenerateSlug(m.ProductName),
})
.ToListAsync();
return new JsonResult(filteredProducts);
}
и в jQuery измените строку на
newproductrow += '<a href = "/post/' + item.slugName + '">';
Пожалуйста, используйте частичное представление и поместите в него логику цикла
for. Затем используйтеAJAX, чтобы обновить егоhtml.