2

I am trying to pass list of class object in my ASP.Net Core 2.1 Controller. I am getting empty object with count 0. I have used attribute [FromQuery], [FromRoute] but the result remain same. My parameter class is as follows:

public class Employee
{
    public int EmployeeCode { get; set; }
    public int EpfNumber{ get; set; }
}

I am trying to get the list of Employee Class in my Controller like this:

[Route("[action]")]
public async Task<ActionResult<int>> GetEmployeeByEmpCode([FromQuery]List<Employee> emp)
{
    //----------Doing my stuff.
    return Ok(1);
}

Here in the emp parameter I am getting empty list. By googling the issue, I got that I need to use [FromUri]. But the [FromUri] is used in Asp.Net WebApi 2, not asp.net core. If I simply add list of string as parameter then it works. The problem is with the class object as peremeter.

My question is how to pass list of class object as peremeter in Asp.Net Core 2.1 controller?

Tony Ngo
  • 19,166
  • 4
  • 38
  • 60
Iswar
  • 2,211
  • 11
  • 40
  • 65
  • You can also utilize the following answer here https://stackoverflow.com/questions/62810278/net-core-web-api-accept-list-of-integers-as-an-input-param-in-http-get-api – mattsmith5 May 19 '21 at 22:40
  • https://stackoverflow.com/questions/62810278/net-core-web-api-accept-list-of-integers-as-an-input-param-in-http-get-api – mattsmith5 May 19 '21 at 22:41
  • https://stackoverflow.com/questions/52892768/openapi-query-string-parameter-with-list-of-objects – mattsmith5 May 19 '21 at 22:43

1 Answers1

2

Try to use FromBody to see if it work. I'm not sure what kind of technology you use (angular, react etc..) to submit the data to the controller

[HttpPost("[action]")]
public async Task<ActionResult<int>> GetEmployeeByEmpCode([FromBody]List<Employee> emp)
{

    return Ok(1);
}
Tony Ngo
  • 19,166
  • 4
  • 38
  • 60
  • I am using Angular 7 as client side technology – Iswar Jun 26 '19 at 10:50
  • Then you can use FromBody – Tony Ngo Jun 26 '19 at 10:50
  • 1
    TypeError: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body. while using FromBody – Iswar Jun 26 '19 at 10:56
  • Then your design is wrong. No one using get request to post List of object. Try to use POST. Check my answer again – Tony Ngo Jun 26 '19 at 10:58
  • There can be requirement of getting from the list of parameter.... Using POST I am able to do my job. But I am not actually posting my data rather I am trying get – Iswar Jun 26 '19 at 11:14
  • https://stackoverflow.com/questions/62810278/net-core-web-api-accept-list-of-integers-as-an-input-param-in-http-get-api – mattsmith5 May 19 '21 at 22:40