2016-11-14 110 views
0

這是AJAX調用,它是調用控制器MVC AJAX不是下載文件

@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> 
} 

此方法導出數據表到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(); 
      } 
     } 

這是我的控制器

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

上述代碼正在進行ajax調用並調用控制器。控制器正在將數據表下載到excel中。

如果我打電話給沒有Ajax調用的控制器,那麼它會下載excel文件,但是當我做ajax調用時,它不下載excel文件。

代碼正在調用正確的控制器和操作,但它不下載文件。

有誰能告訴我這裏有什麼問題。它工作正常,沒有Ajax。

任何幫助,將不勝感激。

在此先感謝。

+1

'數據類型:[文件]類型,你希望從聲明的server.'回數據(HTTP://api.jquery .COM/jque ry.ajax /)只要刪除它。 – Qsprec

+0

是的,我試圖通過刪除,但仍然無法工作 –

+0

我搜索了一下,因爲@madalin說你不能用ajax做到這一點。 Ajax不允許您將文件下載到您的計算機。 [其他線程](http://stackoverflow.com/questions/4545311/download-a-file-by-jquery-ajax) – Qsprec

回答

2

如果返回的URL資源不能在一個Ajax調用更好重定向追加一條鏈接直接下載鏈接,並觸發點擊下載開始

回報從C#

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

創建成功功能的鏈接

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 
+0

感謝您的答覆。我該如何解決這個問題? –

+0

你看過我的回答嗎? – madalinivascu

+0

問題是我沒有任何下載鏈接。我正在創建一個數據表,並將其導出到正在下載文件的excel函數中。所以我應該從控制器傳遞數據表到ajax成功,並且從那裏我應該將該數據表傳遞迴控制器以調用導出到Excel方法? –