0

I am struggling to find a solution to my problem: I have a really simple Web API in C# that GET, POST, PUT and DELETE employees nicely, but everything working with a simple JSON input:

{
 "FirstName": "Sam 10",
 "LastName": "Wicht 10",
 "Gender": "Male",
 "Salary": 140000
}

What I want to do is to POST a lot of employees, like:

"employees": [{
 "FirstName": "Sam 10",
 "LastName": "Wicht 10",
 "Gender": "Male",
 "Salary": 140000
}, {
 "FirstName": "Sam 11",
 "LastName": "Wicht 11",
 "Gender": "Male",
 "Salary": 99000
}]

And in my C# Code, I receive, for instance a List<Employee> containing every employee from JSon and then I loop a For Each ... updating each.

Performance-wise, is this something really bad? Thinking I can limit the List size and avoid running any code if .Count() is higher than X, can you guys please let me know how to retrieve this from the JSON input?

This is the class Employee I have:

public partial class Employee
{
 public int ID { get; set; }
 public string FirstName { get; set; }
 public string LastName { get; set; }
 public string Gender { get; set; }
 public Nullable<int> Salary { get; set; }
}

Should I include a new Class that represents an IEnumerable<Employee> with all the parameters?

This is for learning and testing purposes, and I tried to retrieve [FromBody] List<Employee> myVariableName; returns null;

Cody Gray
246k53 gold badges508 silver badges590 bronze badges
asked Apr 15, 2019 at 0:15
1
  • Your edit removing the bulk of the question's content made it incoherent and rendered the answer meaningless. Do not vandalize your questions. Edits are only intended to clarify and/or add additional information. Commented Apr 18, 2019 at 22:57

1 Answer 1

2

You're getting null because you have an enclosing employee object in your sample json. POST instead:

[{
 "FirstName": "Sam 10",
 "LastName": "Wicht 10",
 "Gender": "Male",
 "Salary": 140000
}, {
 "FirstName": "Sam 11",
 "LastName": "Wicht 11",
 "Gender": "Male",
 "Salary": 99000
}]

And that will match your controller definition of:

public ActionResult Post(List<Employee> employees)
answered Apr 15, 2019 at 0:38

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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