I am struggling with the Response of the Javascript fetch() method. What is my objective: a) to send multiple lines to the backend to save those to a database and b) get a guid in return for further processing. I succeed in objective a (save to database), but the return message fails to materialise. Response.ok is true, but no message is part of the return message. What should I do to accomplish this?
My javascript is:
function saveAll(event) {
event.preventDefault();
var newDeelnemers = new Array();
var lijst = document.querySelectorAll('#tblDeelnemers tbody tr')
lijst.forEach(function (dnmr) {
var row = dnmr;
var deelnemer = {};
var nDnmr = row.children;
//deelnemer.Id = nDnmr[0].innerHTML;
deelnemer.FamilielidFirstName = nDnmr[0].innerHTML;
deelnemer.Achternaam = nDnmr[1].innerHTML;
deelnemer.DOB = nDnmr[2].innerHTML;
deelnemer.Programma = nDnmr[3].innerHTML;
deelnemer.EetMee = nDnmr[4].firstChild.checked;
deelnemer.Dieet = nDnmr[5].innerHTML;
deelnemer.Bedrag = nDnmr[6].innerHTML;
newDeelnemers.push(deelnemer);
});
fetch("/Familiedag/Registreer", {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(newDeelnemers)
}).then(function (response) {
console.log('eerste keer: ' response);
if (response.ok) {
alert('De registratie is gelukt');
//redirect("/Familiedag/RegistreerConfirm?")
}
});
}
The controller
[HttpPost]
public IActionResult Registreer([FromBody] List<FdDeelnemer> newDeelnemers)
{
if (newDeelnemers.Count == 0)
{
return null;
}
Guid registratieGuid = Guid.NewGuid();
foreach (var ndn in newDeelnemers)
{
FdDeelnemer VM = new FdDeelnemer();
VM.RegistratieGuid = registratieGuid;
VM.FamilielidFirstName = ndn.FamilielidFirstName;
VM.Achternaam = ndn.Achternaam;
VM.EetMee = ndn.EetMee;
VM.Dieet = ndn.Dieet;
VM.Programma = ndn.Programma;
VM.DOB = ndn.DOB;
VM.Bedrag = ndn.Bedrag;
VM.CreatedBy = User.Identity.Name;
VM.CreatedOn = DateTime.UtcNow;
_context.Add(VM);
}
Guid geregistreerdeDeelnemers = registratieGuid;
return Json(geregistreerdeDeelnemers);
}
CodePudding user response:
add another .then
that return the json
fetch("/echo/json/", {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
"tes": "data"
})
}).then(function(response) {
return response.json();
}).then(function(json) {
console.log('eerste keer: ', json);
alert('De registratie is gelukt');
//redirect("/Familiedag/RegistreerConfirm?")
});
CodePudding user response:
You can try to return it like that:
return Json(new { AnythingYouWant = geregistreerdeDeelnemers });