0

This is the ajax call which is calling the controller

 @using(Html.BeginForm("ExportData", "ViewData", FormMethod.Post,
     new {
         id = "myform", name = "myform"
     })) {


     <button type = "submit"> Export Raw Policy </button>
 }


 <div id = "divProcessing"> <img src = ~/assets/layouts/layout3/img/loading-spinner-blue.gif" > </p> </div>


 @section Scripts {
     @Scripts.Render("~/bundles/jqueryval")

     <script type = "text/javascript" >

         $(document)
         .ready(function() {

             // Hide the "busy" Gif at load:
             $("#divProcessing").hide();

             // Handle the form submit event, and make the Ajax request:
             $("#myform")
                 .on("submit",
                     function(event) {
                         event.preventDefault();

                         // Show the "busy" Gif:
                         $("#divProcessing").show();
                         var url = $(this).attr("action");
                         var formData = $(this).serialize();
                         $.ajax({
                             url: url,
                             type: "POST",
                             data: formData,
                             dataType: "json",
                             contentType: 'application/json; charset=utf-8',
                             success: function(resp) {

                                 // Hide the "busy" gif:
                                 $("#divProcessing").hide();

                                 // Do something useful with the data:
                                 $("<h3></h3>")
                                     .appendTo("#divResult");
                             }
                         })
                     });
         }); </script>
 }

This method is exporting the datatable into excel

  public static void ExportToExcel(DataTable table)
        {
            try
            {
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.ClearContent();
                HttpContext.Current.Response.ClearHeaders();
                HttpContext.Current.Response.Buffer = true;
                HttpContext.Current.Response.ContentType = "application/ms-excel";
                HttpContext.Current.Response.Write(@"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">");
                HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=Reports.xls");

                HttpContext.Current.Response.Charset = "utf-8";
                HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250");
                //sets font
                HttpContext.Current.Response.Write("<font style='font-size:10.0pt; font-family:Calibri;'>");
                HttpContext.Current.Response.Write("<BR><BR><BR>");
                //sets the table border, cell spacing, border color, font of the text, background, foreground, font height
                HttpContext.Current.Response.Write("<Table border='1' bgColor='#ffffff' " +
                                                   "borderColor='#000000' cellSpacing='0' cellPadding='0' " +
                                                   "style='font-size:11.0pt; font-family:Calibri; background:white;'> <TR>");
                //am getting my grid's column headers
                int columnscount = table.Columns.Count;

                for (int j = 0; j < columnscount; j++)
                {
                    //write in new column
                    HttpContext.Current.Response.Write("<Td>");
                    //Get column headers  and make it as bold in excel columns
                    HttpContext.Current.Response.Write("<B>");
                    HttpContext.Current.Response.Write(table.Columns[j].ToString());
                    HttpContext.Current.Response.Write("</B>");
                    HttpContext.Current.Response.Write("</Td>");
                }
                HttpContext.Current.Response.Write("</TR>");
                foreach (DataRow row in table.Rows)
                {
//write in new row
                    HttpContext.Current.Response.Write("<TR>");
                    for (int i = 0; i < table.Columns.Count; i++)
                    {
                        HttpContext.Current.Response.Write("<Td>");
                        HttpContext.Current.Response.Write(HttpContext.Current.Server.HtmlEncode(row[i].ToString()));
                        HttpContext.Current.Response.Write("</Td>");
                    }

                    HttpContext.Current.Response.Write("</TR>");
                }
                HttpContext.Current.Response.Write("</Table>");
                HttpContext.Current.Response.Write("</font>");
                HttpContext.Current.Response.Flush();
                HttpContext.Current.Response.End();
            }
            catch (Exception ex)
            {
                string abc = ex.ToString();
            }
        }

This is my controller

 public ActionResult ExportData()
        {
            var industryData = _rawDataHlper.GetIndustryData();
            if (industryData != null)
            {
                ExportToExcel((industryData));
            }
            return RedirectToAction("Index");
        }

The above code is making an ajax call and calling a controller. The controller is downloading datatable into excel.

If i call the controller without ajax call then it will download the excel file but when i am making the ajax call then it is not downloading the excel file.

The code is calling the correct controller and action but it is not downloading the file.

Can anyone suggest me what is wrong here. It works fine without ajax.

Any help would be appreciated.

Thanks in advance.

Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61
Owais Ahmed
  • 1,364
  • 1
  • 30
  • 62
  • 1
    `dataType: The type of data that you're expecting back from the server.` declared on the [documentation.](http://api.jquery.com/jquery.ajax/) Just remove it. – Qsprec Nov 14 '16 at 05:32
  • Yup i tried by removing that but still does not work – Owais Ahmed Nov 14 '16 at 05:35
  • I searched a little bit and as @madalin said you are not able to do it with ajax. Ajax doesn't let you download file to your computer. [other thread](http://stackoverflow.com/questions/4545311/download-a-file-by-jquery-ajax) – Qsprec Nov 14 '16 at 05:43

1 Answers1

2

You can't redirect in a ajax call better if you return a url to the resource append that url to a download link and trigger the click for the download to start

return a link from c#

return LinkToAction("Index");// don't know the syntax here sorry

create a link in the success function

 success: function(resp) {
  $('body').append('<a  class="hidden-download" href="'+resp+'" download>hidden<a>').trigger('click').hide();//append it to the body, trigger the click then hide/remove the link
madalinivascu
  • 32,064
  • 4
  • 39
  • 55