0

I am trying to create and download excel file using the following code. It works fine when I use window.open("Export"); in cshtml to call controller method. But it does not work when I make following ajax call. The reason I want to do it using ajax call is because I will be passing parameter to he controller. (I am yet to write logic to use those parameters.)

CSHTML

 var actionUrl = '@Url.Action("Export", "TrendsData")';
$.ajax({
                url: actionUrl,
                type: 'POST',
                cache: false,
                data: { col: FinalColumns.toString() },

                success: function (result) {

                    }
            });

CONTROLLER:

 public void Export(string col)
        {
            var grid = new GridView();
            var data = TempData["InstanceDataList"];
            List<InstanceDataLog> lst = new List<InstanceDataLog>();
            List<EToolsViewer.APIModels.InstanceDataLog> lstrefined = new List<InstanceDataLog>();
            lst=   (List<EToolsViewer.APIModels.InstanceDataLog>)TempData["InstanceDataList"];
            var r= lst.Select(e => new {e.CBlk_Avg_Hz, e.CBlk_Avg_MW}).ToList();

            grid.DataSource =r;
            grid.DataBind();

            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=Trendsdata_" + DateTime.Now.ToString("yyyyMMdd_HHmm") + ".xls");

            Response.ContentType = "application/excel";
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            grid.RenderControl(htw);

            Response.Write(sw.ToString());
            TempData["InstanceDataList"] = data;

            Response.End();

        }

With the above code I am able to call controller method but file does not download whereas problem with using window.open("Export"); is that I can not pass parameters.

I have found out that if I again put window.location = '@Url.Action("Export", "TrendsData",new { col = "a,b,c" })'; in the success method , it works. Is there an explanation for this ? Why do I have to make two calls?

SamuraiJack
  • 5,131
  • 15
  • 89
  • 195
  • You cannot download a file using ajax - refer [this answer](http://stackoverflow.com/questions/16670209/download-excel-file-via-ajax-mvc) –  Nov 29 '16 at 09:28
  • Try to convert the controller method to an ActionResult/FileResult. – Souvik Ghosh Nov 29 '16 at 09:28
  • @StephenMuecke your duplicate hunting skills are way better than mine :) Want me to re-open this so you can close it as a dupe of that one insteaD? – Rory McCrossan Nov 29 '16 at 09:29
  • Go to controller, create the file, return to page and, if all was good, programatically fire window.open("export") using the returned file name. – tao Nov 29 '16 at 09:30
  • @RoryMcCrossan, No, that's a good one as well –  Nov 29 '16 at 09:31
  • @RoryMcCrossan I may have not been able to phrase the question properly. But As you can I see I know how to make this work. What I am asking for is explanation or a better solution. (read the last part of my question. I dont think its a duplicate. – SamuraiJack Nov 29 '16 at 09:32
  • 1
    @Arbaaz - In the accepted answer - _you can't do it through Ajax because JavaScript cannot save files directly to a user's computer (out of security concerns)_ explains it pretty well. –  Nov 29 '16 at 09:36
  • @StephenMuecke what I am confused about is that I am not returning anything AT ALL in my code and yet able to download the file if I make a call in the success method. How does that work? I did not quite get it. Sorry if i sound like a noob, because I am but window.location = path is javascript too right? – SamuraiJack Nov 29 '16 at 09:40
  • `window.location` is a redirect to your `Export()` method (which downloads the file). But you can just remove the ajax call (your effectively calling the method twice, and ignoring the result of the first) –  Nov 29 '16 at 09:45

0 Answers0