Pass the page html via GET Ajax

0

Hello,

I'm trying to download an excel file by passing the html page, but when trying to send the html, it's passing as null.

Ajax

function exportarExcel() {
    var html = $("body").html();
    $.ajax({
        url: location.href = '@Url.Action("ExportExcel")',
        type: 'get',
        data: {
            Html: html,
        },
    });
}

Controller

    [ValidateInput(false)]
    [HttpGet()]
    public void ExportExcel(string Html)
    {
        Classes.Export.ToExcelHtml(Response, Html);
    }

Export

        public static void ToExcelHtml(HttpResponseBase Response, string html)
    {
        Response.ContentType = "application/x-msexcel";
        Response.AddHeader("Content-Disposition", "attachment;filename = Faturamento.xls");
        Response.ContentEncoding = Encoding.UTF8;
        StringWriter tw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(tw);
        Response.Write(html);
        Response.End();
    }
    
asked by anonymous 18.10.2018 / 17:02

1 answer

1

Via GET will not be possible, change your javascript and controller to work with post and use a FileResult to download the file.

function exportarExcel()
{
var html = $("body").html();
    $.ajax({
        url: '@Url.Action("ExportExcel")',
        type: 'post',
        data: { Html: html },
        success: () => { window.location.href = '@Url.Action("Download")' }
    });
}

Controller

[ValidateInput(false)]
[HttpPost]
public void ExportExcel(string html)
{
    //Classes.Export.ToExcelHtml(Response, Html);

    byte[] fileBytes = Encoding.UTF8.GetBytes(html);
    string fileName = "Faturamento.xls";
    TempData["Download"] = File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}

[HttpGet]
public FileResult Download()
{
    return TempData["Download"] as FileResult;
}
    
18.10.2018 / 17:37