0

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: https://i.sstatic.net/qemMK.png

enter image description here

Thanks in advance.

2

1 Answer 1

2

Give this a go, have updated ApplyFilter() to use public properties. Check out the ASP.NET Core 6.0 Model Binding section of the docs which explains how it works.

[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%20Vendor
Sign up to request clarification or add additional context in comments.

2 Comments

Worked just fine mate, thanks a lot. its strange thou that a variable starting with small letter is causing this ?
No worries @AbedAjarmeh good to hear. I've clarified the answer a bit, it wasn't being caused by the camelCase property names!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.