I’m working on a legacy system looking at ways to increase performance. It’s an MVC project with C# backend (upgraded to .net 8) and a Javascript/JQuery front-end. The front-end code is using AJAX to make it’s calls and it’s all working fine but I’m trying to switch it to using Fetch, and I’ve hit a bit of a brickwall. The server side routines all use the following style:
public IActionResult SearchCerts(string Company, string ExpStart, string ExpEnd)
{
...
return PartialView("_SearchResults", Results);
}
and they’re called using:
function SearchCerts() {
$.ajax({
url: "/Certs/SearchCerts",
data: {
Company: document.getElementById("edtSearchCompany").value,
ExpStart: document.getElementById("edtSearchExpires1").value,
ExpEnd: document.getElementById("edtSearchExpires2").value
},
dataType: "html",
async: true,
success: function (data, textStatus, XMLHttpRequest) {
$('#divSearchResults').html(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error");
}
});
}
When I try to use Fetch, all of the parameters come across as null and the only way I seem to be able to pass anything in is to update the server side routine to accept an IFormCollection parameter (pulling out the individual values when needed) and pass in a FormData variable like so:
async function SearchCertsExecute() {
var formData = new FormData();
formData.append('Company', document.getElementById("edtSearchCompany").value);
formData.append('ExpStart', document.getElementById("edtSearchExpires1").value);
formData.append('ExpEnd', document.getElementById("edtSearchExpires2").value);
let Results = await fetch("/Certs/SearchCerts", {
method: 'POST',
body: formData
});
if (Results.ok) {
var data = await Results.text();
$('#divSearchResults').html(data);
} else {
alert("HTTP-Error: " + Results.status);
}
}
I’ve tried creating a Javascript object containing the and then using JSON.stringify but still the server gets nothing but nulls:
var SendData = {
Company: document.getElementById("edtSearchCompany").value,
ExpStart: document.getElementById("edtSearchExpires1").value,
ExpEnd: document.getElementById("edtSearchExpires2").value
};
let Results = await fetch("/Certs/SearchCerts", {
method: 'POST',
body: JSON.stringify(SendData)
});
Can anybody shed any light on what I’m missing?