3

I'm rewriting a page that sends a model containing a file object property to an MVC controller. The page had been transferring the model fine using a submit/postback. However, I can't seem to get the ajax call right to do the same. Here are two approaches that I've tried. Any ideas why neither is working?

Here is the javascript for the first approach, where I assign the file object to the model property:

var model = {
    itemId: $("#itemId").val(),
    itemDescription: $("#itemDescription").val(),
    file: $("#attachment")[0].files[0]
}

$.ajax({
    url: 'Item/SaveItem',
    type: 'POST',
    contentType: false,
    cache: false,
    processData: false,
    data: model,
    async: true,
    success: function (data) {
        //did something good
    },
    error: function (xhr) {
        //did something bad
    }
});

Here is the MVC action method setup to receive the request:

public ActionResult SaveItem(ItemModel model)
{
    SaveModel(model);
}

Here is another approach I've tried, where I try to send the model and file as separate form values:

var model = {
    itemId: $("#itemId").val(),
    itemDescription: $("#itemDescription").val()
}

var formData = new FormData();
    formData.append("model", JSON.stringify(model));
    formData.append("attachment", $("#attachment")[0].files[0]);

$.ajax({
    url: 'Item/SaveItem2',
    type: 'POST',
    contentType: "multipart/form-data",
    cache: false,
    processData: false,
    data: formData,
    async: true,
    success: function (data) {
        //did something good
    },
    error: function (xhr) {
        //did something bad
    }
});

Here's the MVC action method to receive the second request:

public ActionResult SaveItem2(FormCollection form)
{
    var model = form["model"] as ItemModel;
    HttpPostedFileBase attachment = null;

    if (Request.Files.Count > 0)
    {
        attachment = Request.Files[0];
    }

    SaveModel(model);
}
KrimblKrum
  • 183
  • 3
  • 11

0 Answers0