Search code examples
javascriptc#ajaxasp.net-core

Filter Price using Slider in ASP.NET CORE


I'm trying to do price filtering with slider bar. The view will be like this slider bar. I using ajax to filltering the price. Here the code of slider and product view :

<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>

The ajax code so its can filtering the product by price without reloading the page :

<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>

The controller filting the price :

[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);
}

But when I'm adjust on that bar there is nothing happened. I open the network and choose Fetch/XHR, I saw there is a json returned img when I ajust the bar. The json return :

{
    "$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": []
            }
        }
    ]
}

Anyone know the problem why the product not showing according to price ? I believed this is about the for loop. I really appreciate any instruction. Thank you


Solution

  • Most likely the error is because you are using PascalCase properties in jQuery code, and JSON received in camelCase. to fix it change your script to:

    <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);
                    }
                });
            }
        });
    });
    

    Also this line will throw an error:

    newproductrow += '<a href="/post/' + item.SlugGenerator.SlugGenerator.GenerateSlug(item.productName) + '-' + item.productItems[0].productVariations[0].productVarId + '">';
    

    it's better to call SlugGenerator.GenerateSlug in backend as below:

    [HttpGet]
    

    public async Task 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);
    

    }

    and in jQuery change the line to

    newproductrow += '<a href="/post/' + item.slugName + '">';