Search code examples
extjsasp.net-web-apiextjs4

ExtJs standard form submit with jsonData for file download


I'm trying to download a file from WebApi using ExtJs 4.2.3. After reading Extjs 4 downloading a file through ajax call, it looks like my best bet is to use the standard form.submit, however, my data is not passing as expected to the WebApi controller - using the below code, items comes through null.

Controller

public HttpResponseMessage Post(string exportType, List<PcAvailableComponent> items)
{
    var dataToExport = _service.ExportItems(exportType, items);
    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    var stream = new MemoryStream(dataToExport);
    result.Content = new StreamContent(stream);
    result.Content.Headers.ContentType =
        new MediaTypeHeaderValue("application/octet-stream");
    return result;
}

Standard Submit

expForm.submit({
    url: AppRootUrl + 'api/AdminDataExport?exportType=' + exportType,
    //this doesn't work
    jsonData: items,
    waitMsg: 'Generating export...',
    success: function (form, action) {
        if (typeof expWindow !== "undefined") {expWindow.close();}
    },
    failure: function(form, action) {
        Ext.Msg.alert('Failed', 'An error has occurred while generating the export: ' + JSON.parse(action.response.responseText)['ExceptionMessage']);
    }
});

Ajax submit (works but can't get file back)

Ext.Ajax.request({
        url: AppRootUrl + 'api/AdminDataExport',
        params: {
            exportType: 'PricingAndCosting'
        },
        jsonData: items,
        method: 'POST',
        success: function (response) {
            expWindow.close();
            console.log("success!");
    }
});

Solution

  • Ended up abandoning WebApi for this controller, and just passing the JSON as a string, then deserializing it on the server side:

    [HttpPost]
    public ActionResult Index(string exportType, string items)
    {
        var dataToExport = _service.ExportItems(exportType, JsonConvert.DeserializeObject<List<PcAvailableComponent>>(items));
        Response.AddHeader("Content-Disposition", "inline; filename=" + exportType + "_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".xlsx");
        return File(dataToExport, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    }