I am trying to send a POST request using vanilla js Ajax, where I would like to upload a file and some json data.
But I am getting "Internal server error: 500" and the controller parameter is null value.
please help me.
my javascript code
var btnSubmit = document.getElementById("btn-submit");
btnSubmit.addEventListener("click", function () {
var formData = new FormData();
var fileElement = document.getElementById("WaterTankBlueprint");
formData.append("file", fileElement.files[0]);
var aquaFarm = {
Name: document.getElementById("Name").value,
Region: document.getElementById("Region").value,
CEO: document.getElementById("CEO").value
}
var aquaFarmViewModel = {
AquaFarm: aquaFarm,
WaterTankBlueprint: formData
};
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
}
}
};
xhr.open("POST", "/workplace/aqua-farm/add", true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify(aquaFarmViewModel));
});
my viewmodel
public class AquaFarmViewModel
{
public AquaFarm AquaFarm { get; set; }
public IFormFile WaterTankBlueprint { get; set; }
}
my controller
[HttpPost]
[Route("workplace/aqua-farm/add")]
public IActionResult AddAquaFarm([FromBody] AquaFarmViewModel viewModel)
{
// ...... code
return RedirectToAction("AquaFarm");
}