0
Good morning.
I would like to run two Action, one that displays the result on the screen and the other that generates an excel file.
The View that displays the results at its top has the search button and a checkbox to see if you want to generate the excel file. Then, I created a code via ajax to try to execute the two action (the action that displays the result, provides the data for the action that generates the excel file via Tempdata). That is, if the checkbox is checked it executes the Display Action and then calls the Action that generates excel. But when using the Event.preventDefault(); at the click of the button, only displays the results and without the Event.preventDefault(); only performs the download.
View
<script>
$(document).ready(function () {
$("#btnPesquisar").click(function (event) {
event.preventDefault();
$("#loaderDiv").show();
var myformdata = $("#formPesquisar").serialize();
var partes = myformdata.split('&');
partes.forEach(function (parte){
var chaveValor = parte.split('=');
var chave = chaveValor[0];
var valor = chaveValor[1];
if (chave == 'excel') {
if (valor == 'true') {
gerarExcel = true;
}
}
})
$.ajax({
type: "GET",
url: "/Relatorios/Alunos",
data: myformdata,
success: function () {
$("#loaderDiv").hide();
if (gerarExcel == true) {
window.location = "/Relatorios/GerarArquivoExcel";
}
},
error: function (erro) {
alert("Erro: " + erro);
},
complete: function () {
gerarExcel = false;
}
})
})
})
</script>
Action (show results)
public ActionResult ALunos(bool excel = false)
{
List<Alunos> ListaAlunos = new List<Alunos>();
var resultado = _context.Alunos.Where(a => a.Ativo==true);
Thread.Sleep(1500);
if (excel != false)
{
if (excel == true && Alunos.Count > 0)
{
TempData["planilha"] = Util.Funcoes.GerarArquivoExcel(Alunos);
TempData["nomeArquivo"] = "ListaAlunos.xlsx";
}
}
return (View(Alunos));
}
Action(Export Excel)
public FileResult GerarArquivoExcel()
{
byte[] planilhaByte = TempData["planilha"] as byte[];
string nomeArquivo = TempData["nomeArquivo"] as string;
string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Stream planilhaStream = new MemoryStream(planilhaByte);
return File(planilhaStream, contentType, nomeArquivo);
}
and if you open the download in a new tab?
– Leandro Angelo
@Leandroangelo, remains the same thing. If you had a solution to replace the Event.preventDefault();, probably would work. Because with it I can only download, without it I can only display the return. But never the 2.
– Torres
I meant instead of you doing a redirect with the
window.location
, update the content of the current page and make awindow.open
to download the file.– Leandro Angelo
I’ve done it @Leandroangelo and the problem continues.
– Torres