2016-11-14 3 views
0

Download Dies ist die Ajax-Aufruf, der den ControllerMVC Ajax keine Datei

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

Diese Methode wird den Export der Datentabelle in 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(); 
      } 
     } 

Dies ist mein Controller

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

Der obige Code macht einen Ajax Anruf und einen Controller aufrufen. Der Controller lädt Datentabelle in Excel.

Wenn ich den Controller ohne Ajax Anruf anrufe, wird es die Excel-Datei herunterladen, aber wenn ich den Ajax-Anruf mache, dann wird die Excel-Datei nicht heruntergeladen.

Der Code ruft den richtigen Controller und die richtige Aktion auf, lädt die Datei jedoch nicht herunter.

Kann mir jemand vorschlagen, was hier falsch ist. Es funktioniert gut ohne Ajax.

Jede Hilfe wäre willkommen.

Vielen Dank im Voraus.

+1

'datatype: [. Dokumentation] die Art der Daten, die Sie wieder aus dem server.' auf der deklarierten erwartet (http: //api.jquery .com/jque ry.ajax /) Entferne es einfach. – Qsprec

+0

Yup ich versuchte, indem Sie entfernen, aber immer noch nicht funktioniert –

+0

Ich suchte ein wenig und wie @Madalin sagte, Sie sind nicht in der Lage, es mit AJAX zu tun. Ajax lässt Sie keine Datei auf Ihren Computer herunterladen. [anderer Thread] (http://stackoverflow.com/questions/4545311/download-a-file-by-jquery-ajax) – Qsprec

Antwort

2

Sie nicht besser in einer Ajax-Aufruf umleiten können, wenn Sie eine URL auf die Ressource zurückgeben hängen, dass URL zu einem Download-Link und lösen den Klick auf den Download

Rückkehr eine Verbindung von C#

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

erstellen einen Link in der Erfolgsfunktion

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

Danke für die Antwort. Wie kann ich das lösen? –

+0

hast du meine Antwort gelesen? – madalinivascu

+0

Das Problem ist, dass ich keinen Downloadlink habe. Ich erstelle eine Datentabelle und übergebe das, um in die Excel-Funktion zu exportieren, die die Datei herunterlädt. Also sollte ich die Datatable von Controller zu Ajax Erfolg übergeben und von dort sollte ich diese Datentabelle zurück an den Controller übergeben, um die Export to Excel-Methode aufzurufen? –