1

I need to send an array of string from ajax to a controller and I need to return a file to download. I already look and everywhere says that the same solution, but I can not make it work. I have put a break on the controller, but never entered. The controllers are in different project.

SOLUTION
    PROJECT 1
        Controllers
            ApiControllers
            RenderMvcControllers
            SurfaceControllers
                ExportController
    PROJECT 2


function GetData() {

var stringArray = new Array();
stringArray[0] = "item1";
stringArray[1] = "item2";
stringArray[2] = "item3";
var postData = { values: stringArray };

$.ajax({
    type: "POST",
    url: "/umbraco/Surface/Export/HandleDownloadFile",
    data: postData,
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function (data) {
        alert();
        alert(data.Result);
    },
    error: function (data) {
        alert("Error: " + data.responseText);
    },
});
}

class ExportController : SurfaceController
{

    [HttpPost]
    public ActionResult HandleDownloadFile(string[] productList)
    {
        return CurrentUmbracoPage();
    }
}
avechuche
  • 1,470
  • 6
  • 28
  • 45
  • You have specified `contetType: 'json'`, therefore you must stringify the data `data: JSON.stringify(postData),` but your method needs to be `public ActionResult HandleDownloadFile(string[] values)` (or use `var postData = { productList: stringArray };`) –  May 02 '16 at 22:32

1 Answers1

8

If you are sending array values via AJAX, you'll need to ensure that the traditional attribute is set to true (which allows this behavior) and that your parameter is named to match what MVC expects that it should be productList :

// This is important for passing arrays
traditional: true,

Secondly, since you are posting this to a different project, you may need to explicitly define where the project is running by using an absolute URL (as a relative one would be used by default and would likely point to your current project) :

url: "{your-other-project-url}/umbraco/Surface/Export/HandleDownloadFile",

Finally, you may want to try removing the contentType attribute as that is used to define what the server expects to receive in it's response. Since you aren't expecting JSON back (and instead are expecting a file), you could consider removing it.

$.ajax({
    type: "POST",
    // Consider making the URL absolute (as it will be relative by default)
    url: "/umbraco/Surface/Export/HandleDownloadFile",
    // This is important for passing arrays
    traditional: true,
    // Make sure that productList is used as it matches what your Controller expects
    data: { productList: stringArray }.
    dataType: "json",
    success: function (data) {
        alert(data.Result);
    },
    error: function (data) {
        alert("Error: " + data.responseText);
    },
});
Rion Williams
  • 74,820
  • 37
  • 200
  • 327