I am using jQuery to store some data in my database. I am using an MVC 5 application (ASP.NET).
The data being send is a id int parameter and a array of data objects.
When using $.post for sending the data to the server-side all seems to be working, however when using the $.ajax variant, I get an error about a null parameter which is not optional.
This has probably something to do with the options I am setting in my ajax call, though I am not a JQuery or Javascript expert so I am not entirely sure.
The 2 calls:
Working:
$.post("/Projects/InventorySaveChanges", { projectId: _projectId, data: JSON.stringify(data)}, function (data) {
if (data.Result) {
// Success code
}
else {
// Error code
}
}).error(function (a, b) {
// Error code
});
Not working:
var obj = {};
obj.projectId = _projectId;
obj.data = JSON.stringify(data);
$.ajax({
url: '/Projects/InventorySaveChanges',
type: 'POST',
processData: false,
contentType: false,
data: obj,
success: function (data, status, jqxhr) {
// Success code
},
error: function (jqxhr, status, msg) {
// Error code
}
});
The MVC controller endpoint:
[HttpPost]
public ActionResult InventorySaveChanges(int projectId, string data)
{
// .. Handle data
}
Using the ajax call like this is actually an additional question, besides the current data I also want to store files to the server. The files are being stored in a jQuery variable as follow:
var _roomFileUploads = new FormData();
var file = $('#addPictureFile')[0].files[0];
_roomFileUploads.append(fileName + "|" + _editingRoom.Id, file);
At first I tried to send the files as parameters in the $.post function:
$.post("/Projects/InventorySaveChanges", { projectId: _projectId, data: JSON.stringify(data), fileUpload: _roomFileUploads }, function (data) {
if (data.Result) {
// Success code
}
else {
// Error code
}
}).error(function (a, b) {
// Error code
});
MVC Endpoint:
public ActionResult InventorySaveChanges(int projectId, string data, List<IFormFile> fileUpload = null)
{
// Handle data..
}
The IFormFile interface:
public interface IFormFile
{
string ContentType { get; }
string ContentDisposition { get; }
NameValueCollection Headers { get; }
long Length { get; }
string Name { get; }
string FileName { get; }
Stream OpenReadStream();
void CopyTo(Stream target);
Task CopyToAsync(Stream target, CancellationToken cancellationToken = default);
}
The above gives me the following error (when adding the fields as parameter to my endpoint):
Though, I am not sure if this is the way to go to post the files to the server-side. I am building on top of old code which I am trying to keep (mainly) intact, that is why I am trying to send the files as a parameter. Perhaps there is also a way to include the files in the data array object?
Or should I append all the parameter data to the _roomFileUploads = new FormData() variable as well and handle it with Request.Form on the server-side?

IEnumerable<System.Web.HttpPostedFileBase> fileUploadinstead ofList<IFormFile>