Passing multiple JSON objects at once to ASP.NET API

I have multiple objects that each represent a task. They get saved in the local storage and I needed to find a way to send them all at once to the ASP.NET API when clicking a “Sync” button in the front-end:

{"planid":543,"starttime":"2019-01-07T09:41:17.617Z","duration":2}

{"planid":559,"starttime":"2019-01-07T09:43:11.237Z","duration":10}

This is my solution which is based on this Stackoverflow discussion:

First, in React I created a JSON object which ended up looking like this:

{"taskDone":[{"planid":543,"starttime":"2019-01-07T09:41:17.617Z","duration":2},{"planid":559,"starttime":"2019-01-07T09:43:11.237Z","duration":0}]}

In the React code, I simply added “taskDone” to the JSON string to create a parent object. I guess I could have created an actual object and serialized it, but this worked just as well.

var tasks = '{"taskDone":' + localStorage.getItem("tasks") + '}';

fetch(API + 'plannedtasks',
{
	method: 'POST',
	headers: {
		  'Accept': 'application/json',
		  'Content-Type': 'application/json'
	},
	body: tasks
}).then(function(response) {
  console.log(response);
})
.catch(function(error) {
  console.log(error);
});   

In ASP.NET we create 2 model classes. The first one “TasksDoing” is for the actual objects. The second one “allCompletedTasks” is the parent object that has a relation with the TasksDoing class. Notice the name “taskDone” which is the same as the parent object name.

public class TasksDoing
{
	[Key]
	public int workid { get; set; }
	public int planid { get; set;  }
	public DateTime starttime { get; set; }
	public int duration { get; set; }
}

public class allCompletedTasks
{
	public TasksDoing[] taskDone { get; set; }
}

This is how the code looks like for saving the first task object. To add all the tasks we could use a foreach loop.

[HttpPost]
public IActionResult Post([FromBody] allCompletedTasks values)
{
	Console.WriteLine("RECEIVED planid: " + values.taskDone[0].planid);

	_context.TasksDoing.Add(values.taskDone[0]);
	_context.SaveChanges();

	return Ok(values);
}

While writing this article I researched some more and came across this article which also describes how to do it
https://www.dotnetcurry.com/aspnet/1278/aspnet-webapi-pass-multiple-parameters-action-method

Leave a Reply

Your email address will not be published. Required fields are marked *