Home > front end >  How to pass an array of objects through a query string and read them in asp.net Controller
How to pass an array of objects through a query string and read them in asp.net Controller

Time:04-03

I am building an API to generate Invoice Number.

I have the following InvItem class

public class InvItem
{
    public string ItemCode;
    public double Quantity;
    public double SaleValue;
}

I have the following Controller method

    [Route("api/InvoiceMaster/GetInvoiceNum")]
    [HttpGet]
    public IActionResult GetInvoiceNum(            
        string xDateTime,
        string BuyerName,
        double TotalBillAmount,            
        InvItem[] items
        )
    {


        ...
        var invItems = new List<InvItem>();
        invItems.AddRange(items);
        ...
        return Ok();            
    }

Invoice can have one or more items. Now I want to call that method from postman (or any other application) using GET request.

I have already built that method using POST request and reading parameters from request body. But the requirement here is STRICTLY Get Request.

I have tried the following url but cannot get the value of items in controller's action method 'GetInvoiceNum'

https://localhost:44365/api/InvoiceMaster/GetInvoiceNum?xDateTime=2020-01-01 12:00:00&BuyerName=elon&TotalBillAmount=1519&items[0].ItemCode=001897&items[0].Quantity=1&items[0].SaleValue=19&items[1].ItemCode=002899&items[1].Quantity=1&items[1].SaleValue=1500

How can I pass this array of objects to api?

CodePudding user response:

You have to add from [FromQuery]

public IActionResult GetInvoiceNum(            
        [FromQuery] string xDateTime,
        [FromQuery] string BuyerName,
        [FromQuery] double TotalBillAmount,            
        [FromQuery] InvItem[] items
        )

and convert fields to properties by adding getters/setters

public class InvItem
    {
        public string ItemCode { get; set; }
        public double Quantity { get; set; }
        public double SaleValue { get; set; }
    }
  • Related