Walter Lockhart
Walter Lockhart

Reputation: 1293

ASP.NET Core 2.2 [FromQuery] not receiving string value

I pass the following parameters:

GET: http://localhost:51796/api/strategies/page?pageNumber=1&pageSize=5&term=stress

to the following endpoint:

    [HttpGet("page")]
    public async Task<IActionResult> PagedListAsync([FromQuery]PageParams pageParams) { }

PageParams is defined as:

public class PageParams
{
    public string Term { get; set; }

    private const int MaxPageSize = 50;
    private int pageSize = 10;

    public int PageNumber { get; set; } = 1;

    public int PageSize
    {
        get { return pageSize;}
        set { pageSize = (value > MaxPageSize) ? MaxPageSize : value;}
    }
}

the values received in pageParams are:

PageNumber 1
PageSize 5
Term ""

For some reason the field Term is "" and not "stress".

Can someone help me please?

Upvotes: 1

Views: 331

Answers (1)

Steve Land
Steve Land

Reputation: 4862

Specify the [FromQuery] decorator on the individual properties, not the parent class.


    public class PageParams
    {
        private const int MaxPageSize = 50;
        private int pageSize = 10;

        [FromQuery]
        public string Term { get; set; }

        [FromQuery]
        public int PageNumber { get; set; } = 1;

        [FromQuery]
        public int PageSize
        {
            get { return pageSize;}
            set { pageSize = (value > MaxPageSize) ? MaxPageSize : value;}
        }
    }

See example in docs: https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-2.2#sources

Upvotes: 1

Related Questions