How can I implement a price filter on my website to filter cars based on a price range (‘from price’ and ‘to price’)?

Even though I set the price range to ‘from price’ = 100,000 and ‘to price’ = 150,000, the filter shows cars with prices outside this range. I suspect there might be an issue with how the price filtering is applied, or the data might not be correctly parsed or compared.

Frontend Implementation:

onInputChange(event: any, field: string): void {
 this.filter[field] = event.target.value;
}
applyFilter() {
 this.filter['car_type'] = "17";
 const requestPayload = { Filter: this.filter };
 this.Service.getfiltercar(requestPayload).subscribe(
 {
   next: (response: any) => {
     this.newcar = response
   },
   error: (error: any) => {
     console.error('There was an error!', error);
   }
 });
}

Backend Implementation:

case "price":
  var fromPriceString = filters.FirstOrDefault(f => f.Key == "FromPrice").Value;
  var toPriceString = filters.FirstOrDefault(f => f.Key == "ToPrice").Value;

  if (decimal.TryParse(fromPriceString, out var fromPrice) && decimal.TryParse(toPriceString, out var toPrice))
  {
     query = query.Where(c => decimal.Parse(c.price) >= fromPrice && decimal.Parse(c.price) <= toPrice);
  }
  break;

I expected that the filter would correctly display only those cars whose prices fall within the range specified by FromPrice and ToPrice.

I also expected that the filter would correctly handle cases where either FromPrice or ToPrice is not provided.

1

I also expected that the filter would correctly handle cases where either FromPrice or ToPrice is not provided.

It will not, empty form fields will either be null or the empty string, neither of which will convert to decimal.

Assuming query is IQuertable<TEnity> then you can build a query incrementally:

if (decimal.TryParse(fromPriceString, out var fromPrice) {
  query = query.Where(x => x.Price >= fromPrice;
}
if (decimal.TryParse(toPriceString, out var toPrice) {
  query = query.Where(x => x.Price <= toPrice;
}

The other approach is to have a default value:

var fromPrice = decimal.TryParse(fromPriceString, out var p)
                ? p
                : DefaultFromPrice;

You could try below code:

CarController.cs:

using Microsoft.AspNetCore.Mvc;

namespace CarFilterApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class CarsController : ControllerBase
    {
        // Mock data for testing
        private List<Car> cars = new List<Car>
        {
            new Car { Id = 1, Name = "Car A", Price = 120000 },
            new Car { Id = 2, Name = "Car B", Price = 80000 },
            new Car { Id = 3, Name = "Car C", Price = 135000 },
            new Car { Id = 4, Name = "Car D", Price = 150000 },
            new Car { Id = 5, Name = "Car E", Price = 95000 }
        };

        [HttpPost("filter")]
        public IActionResult FilterCars([FromBody] FilterRequest request)
        {
            var query = cars.AsQueryable();

            if (decimal.TryParse(request.Filter["FromPrice"], out var fromPrice))
            {
                query = query.Where(c => c.Price >= fromPrice);
            }

            if (decimal.TryParse(request.Filter["ToPrice"], out var toPrice))
            {
                query = query.Where(c => c.Price <= toPrice);
            }

            return Ok(query.ToList());
        }
    }

    public class Car
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
    }

    public class FilterRequest
    {
        public Dictionary<string, string> Filter { get; set; }
    }

}

angular:

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';



@Component({
  selector: 'app-car-filter',
  standalone: true,
  imports: [CommonModule, FormsModule, HttpClientModule],
  templateUrl: './car-filter.component.html',
  styleUrl: './car-filter.component.css'
})
export class CarFilterComponent {
  fromPrice: number = 0;
  toPrice: number = 0;

  newcar: any[] = [];

  filter: { [key: string]: string } = {
    car_type: '',
    FromPrice: '',
    ToPrice: ''
  };
  
  constructor(private http: HttpClient) { }

  onInputChange(event: any, field: string): void {
    this.filter[field] = event.target.value;
  }

  applyFilter() {
    this.filter['car_type'] = "17"; // Example car type

    const requestPayload = { Filter: this.filter };

    console.log('Applying filter with:', requestPayload);

    this.http.post('https://localhost:7073/api/cars/filter', requestPayload).subscribe(
      (response: any) => {
        this.newcar = response;
        console.log(this.newcar);
      },
      (error) => {
        console.error('There was an error!', error);
      }
    );
  }
}

In your code, you were parsing the car prices using decimal.Parse(c.price). If any price is not in a decimal format, it could have caused an issue, leading to incorrect filtering. use decimal.TryParse() instead of directly parsing price values.
In your frontend code, there may have been a situation where FromPrice or ToPrice was sent as an empty string or null. The backend might have failed to handle these cases properly.to fix that in the backend only applies the filter if FromPrice or ToPrice can be successfully parsed, meaning invalid or missing values are ignored instead of causing errors.

Test Result:

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật