Home > Enterprise >  ASP.NET Core 6 [FromQuery] return null values when binding to object
ASP.NET Core 6 [FromQuery] return null values when binding to object

Time:04-12

A picture is worth a thousand words - as you can see in the following screenshots, I'm not able to retrieve the parameters in the query string and bind them to the ApplyFilter model. I've tried [BindQuery], [BindProperty] and [Bind], but unfortunately no luck at all. I keep getting null values on the filter parameter even though the parameters are passed to the QueryString.

https://localhost:7061/getallproducts?withproductoptions=true&categoryid=1&pricefrom=1&priceto=30&vendorname=ArtWithLight

Code:

public class ProductsController : ControllerBase
{
    private readonly IProductRepositery _prodRepo;

    public ProductsController(IProductRepositery prodRepo)
    {
        _prodRepo = prodRepo;
    }

    [HttpGet]
    public async Task<ActionResult<ProductDto>> GetAllProducts([FromQuery]ApplyFilter? filters)
    {
        return Ok(await _prodRepo.GetAllProductsAsync(filters));
    }
}

public class ApplyFilter
{
    public ApplyFilter()
    {
    }

    [FromQuery(Name = "categoryid")]
    List<int>? categoryIds { get; set; }
    [FromQuery(Name = "withproductoptions")]
    bool? withProductOptions { get; set; }
    [FromQuery(Name = "pricefrom")]
    decimal? priceFrom { get; set; }
    [FromQuery(Name = "priceto")]
    decimal? priceTo { get; set; }
    [FromQuery(Name = "vendorname")]
    string? vendorName { get; set; }
}

See screenshot: enter image description here

Thanks in advance.

CodePudding user response:

Give this a go, have updated ApplyFilter().

[ApiController]
[Route("[controller]")]
public class ProductsController : ControllerBase
{
    [HttpGet]
    public IActionResult Get([FromQuery] ApplyFilter filters)
    {
        return Ok();
    }

    public class ApplyFilter
    {
        public List<int>? CategoryIds { get; set; }
        public bool? WithProductOptions { get; set; }
        public decimal? PriceFrom { get; set; }
        public decimal? PriceTo { get; set; }
        public string? VendorName { get; set; }
    }
}

Request example:

/Products?CategoryIds=1&CategoryIds=2&WithProductOptions=true&PriceFrom=10&PriceTo=20&VendorName=The Vendor
  • Related