Pass page html via GET Ajax

Asked

Viewed 128 times

0

Hello,

I am trying to download an excel file by passing the html of the page, but when trying to send the html, it is 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();
    }
  • show your Classes.Export.ToExcelHtml()

  • 1

    And via GET will be complicated...

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;
}
  • But it is possible to download the file using the [Httppost]?

  • 1

    yes, I will edit the answer, with the information of your class that is only making a replay

  • also tried something similar to this case: https://stackoverflow.com/questions/12916340/complex-type-is-getting-null-in-a-apicontroller-parameter but did not roll

  • @Flavio see my edition

Browser other questions tagged

You are not signed in. Login or sign up in order to post.