0

I am passing a list to my controller to generate an Excel file that need to be downloaded by user. The list am passing can be upto 10000 records

Here is my controller method

[HttpPost]
    public FileResult Result(List<List> Content)
    {            
        var stream = new MemoryStream();
        var serializer = new XmlSerializer(typeof(List<Content>));

        var data = Transformer.TransformToExcelFormat(Content);
        //We turn it into an XML and save it in the memory
        serializer.Serialize(stream, data);
        stream.Position = 0;
        //We return the XML from the memory as a .xls file
        return File(stream, "application/vnd.ms-excel", "Template.xls");
    }

Here is my java script

   var Content = { "Content": ItemList() };
    var pack = ko.toJSON(Content);

    $.ajax({
        url: baseUrl + '/Client/Result',
        type: "POST",
        datatype: "json",           
        data: pack,
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
        // Just wondering how to handle success result.
        }
    });

I will appreciate suggestion that will lead to success.

Thanks.

tereško
  • 58,060
  • 25
  • 98
  • 150
user1656779
  • 241
  • 1
  • 2
  • 7

1 Answers1

1

You can't download a file via ajax.

One way to do it is to serialize the params (the list) and use window.location.assign:

var serialized = $.param(pack);

window.location.assign(baseUrl + '/Client/Result' + '?' + serialized);

A possible problem that you'll encounter because you have a lot of records, could be that you'll exceed the maximum query string length.

Also, remove the [HttpPost] from the controller method;


Another way would be to send an ajax request, generate the file and save it, then return a download url of that saved file, and programatically create an anchor element in js and click it.

Hope i could help, or at least point in the right direction.

[1]http://api.jquery.com/jquery.param/

[2]Download File Using Javascript/jQuery

Community
  • 1
  • 1
Cristi Pufu
  • 9,002
  • 3
  • 37
  • 43