0

I want to post files and other data in one request using axios and asp.net mvc

javascript:

var otherData = {
   Id: 123,
   Name: "Sam"
};

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

// I have tried these cases
// case 1:
// formData.append("request", otherData);
// case 2:
// formData.append("Id", otherData.Id);
// formData.append("Name", otherData.Name);

axios.post("/../MyAction", formData, { headers: {"Content-Type": "multipart/form-data"} })
.then(...);

Action:

public ActionResult MyAction(IEnumerable<HttpPostedFileBase> files, MyModel request)
{
}

public class MyModel
{
    public int Id {get; set;}
    public string Name {get; set;}
}

The files received, but the other data not

How should I adjust my code to let it working?

By the way, can I let the HttpPostedFileBase in the model like:

public class MyModel
{
   public int Id {get; set;}
   public string Name {get; set;}
   public IEnumerable<HttpPostedFileBase> Files {get; set;}
}
Max
  • 4,439
  • 2
  • 18
  • 32

1 Answers1

-1

I am not sure what axios does. But with jQuery ajax api, you can send files and other values together using FormData over ajax.

$(function () {

    $("#saveBtn").click(function(e) {
        e.preventDefault();
        var url = "@Url.Action("Create", "Home")";
        var fdata = new FormData();

        fdata.append("Id", 123);
        fdata.append("Name", "Sam");

        var fileInput = $('#Files')[0];
        var files = fileInput.files;
        for (var i = 0; i < files.length; i++) {
            fdata.append("files", files[i]);
        }

        $.ajax({
            type: 'post',
            url: url,
            data: fdata,
            processData: false,
            contentType: false
        }).done(function(result) {
            // do something with the result now
            console.log(result);
        });

    });

});

And in your HttpPost action method, you can use the MyModel class as parameter type and model binder will be able to properly bind the posted data

[HttpPost]
public ActionResult Create(MyModel model)
{
  // check model.Files & model.Id
  // to do  :Return something
}

I am using the Url.Action method to generate the correct relative path to the action method. It will work if this script code is inside a razor view. If this code is inside an external javascript file, follow the method described in this post.

Shyju
  • 214,206
  • 104
  • 411
  • 497