c# – Prealoder when requesting download

Question:

I'm returning a pdf from a Custom ActionResult

response.ContentType = "application/pdf";
response.AddHeader("Content-Disposition", "attachment; filename=teste.pdf");

And I would like to know how I could make a preloader while the server processes this download

[Edit]

As requested, the code of the link I make the download request

@Ajax.ActionLink("Print", "Report", new { id = 20 }, new AjaxOptions { 
        Confirm="Are you cure?",
        HttpMethod="GET",
        LoadingElementId="divLoading"
    })

Answer:

Suppose you already have the preloader ready (html, css, js) and you just need to call and hide it at download time. If not, here's an example.

You can use ajax to call your ActionResult and call your preloader ao mesmo tempo.

<script>
    $(".downloadAnexo").click(function () {
        $("#divPreloader").fadeIn();//Chama o preloader
        $.ajax({
            url: '@Url.Action("DownloadFile")?id=' + 1,//Sua ActionResult
            type: 'GET',
            success: function () {
                $("#divPreloader").hide();//Esconde o preloader em caso de sucesso
            }, error: function () {
                $("#divPreloader").hide();//Esconde o preloader em caso de erro
            }  
        });
    });
</script>

See an example on dotNetFiddle.

Edit

Using Ajax.ActionLink you have both OnBegin and OnComplete options. You just call the functions to show and hide the preloader . Would be like this:

@Ajax.ActionLink("Print", "Index", new { id = 20 }, new AjaxOptions
{
    Confirm = "Are you cure?",
    HttpMethod = "GET",
    LoadingElementId = "divLoading",
      OnBegin = "onAjaxBegin",//Chamo a função onAjaxBegin
    OnComplete = "onAjaxComplete"//Quando completar, chamo a função onAjaxComplete
})

And you create the functions to do what you want:

<script>
   function onAjaxBegin() {
            $('#divPreloader').fadeIn();
        }

        function onAjaxComplete() {
            $('#divPreloader').hide();
        }
    </script>
Scroll to Top