0

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):

enter image description here

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?

6
  • Do you need to upload multiple files or single file? Commented Oct 1, 2019 at 14:45
  • Data is now being stored in an array, so each record is pushed to an array, one record can have 1 file, but because all records are stored in a array there are multiple files (records) stored to the database at once. So the data variable contains rooms which is an array, each room has 1 file. The data variable used to consist only of text data so it was never a problem, though now it is giving issues because files are added (stored) as well. Commented Oct 1, 2019 at 14:48
  • have you tried my answer? Commented Oct 1, 2019 at 14:55
  • Not yet, will get back to you once I have implemented it! Thank you. Commented Oct 1, 2019 at 15:18
  • It is working, thank you! Had to make one small adjustment since I am using .NET 4.x instead of .Net core: IEnumerable<System.Web.HttpPostedFileBase> fileUpload instead of List<IFormFile> Commented Oct 2, 2019 at 10:44

1 Answer 1

1

EDIT

The Code is modified for multiple files.

var obj= new FormData();
obj.append("projectId", 1);
obj.append("data", data);

for (var i = 0; i < $('#file')[0].files.length; i++) {
     model.append("fileUpload", $('#file')[0].files[i]);
}

$.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
    }
});

Controller Code.

public ActionResult InventorySaveChanges(int projectId, string data, List<HttpPostedFileBase> fileUpload = null)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.