HTTP Patch partial update with more complex object, ASP.NET Core API & Angular 8
I’ll post where I’ve gone so far, I am using ASP.NET Core’s JsonPatchDocument for patching.
Angular part:
// Prepare objects for update, property total and timesheetDetails.timesheetDetailDates
// quantity and shortDescription need to be updated.
const timesheetDetails = [
{timesheetDetails: {timesheetDetailDates: details}}
];
const total = [
{total: this.timesheetDetailsForm.controls.total.value }
];
this.updateOnSubmit(timesheetDetails, total);
}
updateOnSubmit(details: any, total: any) {
const x = JSON.stringify(details);
const y = JSON.stringify(total);
const body = [{
op: "replace",
path: "/timesheetDetails",
value: x
},
{
op: "replace",
path: "/total",
value: y
}];
this.tService.patchTimesheet(this.timesheetId, body).subscribe((date) => {
if (date !== null) {
//...
});
}
This is what the request looks like:
And for the backend:
[HttpPatch("{id}", Name = "PatchTimesheet")]
public async Task<IActionResult> PatchTimesheet(int id, [FromBody] JsonPatchDocument<Timesheet> timesheetPatchDocument)
{
var timesheet = await _timesheetManager.GetTimesheet(id);
timesheetPatchDocument.ApplyTo(timesheet);
return Ok(timesheet);
}
What ApplyTo() returns is:
The value ‘[{"timesheetDetails":{"timesheetDetailDates":[[
{"quantity":4,"shortDescription":"Work description for 14.01."},
{"quantity":0,"shortDescription":"Work description for 15.01"},
{"quantity":2,"shortDescription":""},
{"quantity":0,"shortDescription":""}]]}}]…’ is invalid for target
location.
Here is what my actual model looks like:
public class Timesheet
{
public int Id { get; set; }
public int TimesheetStatusId { get; set; }
public String Unit { get; set; }
public List<TimesheetDetails> TimesheetDetails {get; set;}
public int Total { get; set; }
}
So you got the idea, Timesheet has a collection of timesheet details which has a collection of timesheet detail dates.
I passed total and timesheetdetails.timesheetdetaildates, quantity and shortDescription properties, they all exist in my model class as well.
I know I’m missing something here, haven’t messed with patching before, but what I could find were only simple examples.
Source: Angular Questions