Multiple parameters on jquery ajax call asp.net

偶尔善良 提交于 2019-12-08 13:02:10

问题


I am trying to pass two parameters on an ajax call. I already tried several ways suggested on StakeOverflow but none worked. Here is my method signature on controller:

[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase[] files, string[] usersToShare)

Here is my function:

function uploadFile() {
        var formData = new FormData();
        var totalFiles = document.getElementById("files").files.length;

        for (var i = 0; i < totalFiles; i++) {
            var file = document.getElementById("files").files[i];
            formData.append("files", file);
        }

        //get the selected usernames (email) to share the file
        var selectedUsers = [];
        $("#costumerUsersListSelect :selected").each(function () {
            selectedUsers.push($(this).val());
        });

        $.ajax({
            type: 'post',
            url: '/ManageFiles/UploadFile', 
            data: "files=" + formData + "usersToShare=" + selectedUsers,
            dataType: 'json',
            contentType: false,
            processData: false,
            success: function (data) {                    
            },
            error: function (error) {                  
            }
        });
    }

So I want to pass to the controller the formData and the selectedUsers. If I pass just the formData (Data: formData) everything works but I need to pass the selectedUsers too.

Here what I already tried without any success:

data: JSON.stringify({ files: formData, usersToShare: selectedUsers }),
data: { files: formData, usersToShare: JSON.stringify(selectedUsers)},
data: "files=" + formData + "&usersToShare=" + selectedUsers,
data: "files=" + formData + "usersToShare=" + selectedUsers,

I am not sure if this is a syntax issue.

Thanks in advance for any help.


回答1:


Instead of:

data: "files=" + formData + "usersToShare=" + selectedUsers,

append the selectedUsers in formData and send only formData to the server like:

data: formData, 

and try again.




回答2:


You need to use different keys for each value you append to formData, and then just append both files and users the same way

function uploadFile() {
  var formData   = new FormData();
  var allFiles   = $("#files").get(0).files;

  for (var i = 0; i < allFiles.length; i++) {
    formData.append("files_" + i, allFiles[i]);
  }

  $("#costumerUsersListSelect :selected").each(function(_,i) {
    formData.append('user_' + i, this.value);
  });

  $.ajax({
    type: 'post',
    url: '/ManageFiles/UploadFile',
    data: formData,
    dataType: 'json',
    contentType: false,
    processData: false,
    success: function(data) {},
    error: function(error) {}
  });
}


来源:https://stackoverflow.com/questions/44997194/multiple-parameters-on-jquery-ajax-call-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!