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: