Use of ajax ASP.NET MVC

1

I'm exporting to Excel

But I need to use ajax , because I need that when I give in Exportar a Excel leave me in the same view

This is from my controller where I have: My ActionResult of index and void where I export to excel

    using RecursosHumanos.Models;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;

    namespace RecursosHumanos.Controllers
    {    
        [Authorize]
        public class HomeController : Controller
        {
            private RecursosHumanosEntities db = new RecursosHumanosEntities();

     public ActionResult Index()
            {
                return View();
            }

            public void ExportarExcel2(string[] Deducciones,List<DeduccionesEmpleadoViewModel> DeduccionesZ)
            {


            }

    }
   }

This in my view, is where I need the ajax

 @{ 
        ViewBag.DashBoard = "active";
        ViewBag.Title = "DashBoard";

    }
    @{ 
        int i = 0;
    }

    @section _Header
    {
        <!-- Page header -->
        <div class="page-header page-header-default">
            <div class="page-header-content">
                <div class="page-title">
                    <h4><i class="icon-arrow-left52 position-left"></i> <span class="text-semibold">Home</span> - Dashboard</h4>
                </div>

                <div class="heading-elements">
                </div>
            </div>


            <div class="breadcrumb-line">
                <ul class="breadcrumb">
                    <li><a href="/Home/Index"><i class="icon-home2 position-left"></i> Home</a></li>
                    <li class="active">Dashboard</li>

                </ul>



                @*<ul class="breadcrumb-elements"></ul>*@
                <ul class="breadcrumb-elements">
                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                            <i class="icon-gear position-left"></i>
                            Opciones
                            <span class="caret"></span>
                        </a>

                        <ul class="dropdown-menu dropdown-menu-right">

                            @*<li><a href="@Url.Action("ExportarExcel","Planilla", new { FechaInicio=ViewBag.FechaInicio, FechaFin= ViewBag.FechaFin , TipoPlanillaid = ViewBag.TipoPlanillaId, NumeroPlanillas = ViewBag.PlaNumero, Deducciones = ViewBag.Deduccionesp})"><i class="icon-file-excel position-left"></i> Exportar a Excel</a></li>*@
                            <li><a id="BotonEnviar" href="javascript:document.getElementById('frm-planilla').submit()"><i class="icon-file-excel position-left"></i> Exportar a Excel</a></li>

                        </ul>
                    </li>
                </ul>

            </div>
        </div>
   <form action="@Url.Action("ExportarExcel2")" method="post" id="frm-planilla">
   @for (int i = 0; i < 5; i++)
   {
     <input type="text" name="[@i].DedId" value="@i" />
   }
</form>

at the moment of giving it in the option to export to excel leave me in the same view

    
asked by Antonio Diaz 23.11.2018 в 18:33
source

2 answers

0

With ajax it is not possible to export the file, you must do it through an iframe to which you must pass the parameters by GET. In the following way I do it to export files to excel regardless of the language you are using on the server side.

/*Si no existe el iframe lo agrego al dom*/
if($('#iframe-download').length==0)
        $('body').append('<iframe id="iframe-download" style="border:0px;display:none"/>');

/*modifico los parametros de la URL de mi script que genera el archivo de descargas*/    
$('#iframe-download').attr('src',url+'?param1=valor1&....');
    
answered by 23.11.2018 в 19:34
0

Good to generate a report in c # I use the complete ClosedXML

Here is a small tutorial link

I share how I make the report run with Ajax.

public ActionResult Reporte()
    {


        string nombre = "Nombre de tu archivo";

        //aquí closed xml genera el archivo Excel
        var workbook = ReporteUno.GenerarReporte();

        //Genera una llave única para el archivo quevas abrir
        string handle = Guid.NewGuid().ToString();

        // Salvas el archive en alguna parte de la memoria de forma temporal
        using (MemoryStream stream = new MemoryStream())
        {
            workbook.SaveAs(stream);
            stream.Position = 0;
            TempData[handle] = stream.ToArray();
        }

        //Aca guardas el nombre y la llave del archivo que vas a ganerar
        GuiasArgs nueco = new GuiasArgs();
        nueco.FileGuid = handle;
        nueco.FileName = nombre;
        return Json(nueco, JsonRequestBehavior.AllowGet);
    }

Now you must use the following javascript. In this case I use Jquery

$.ajax({
                       datatype: 'JSON',
                       cache: false,
                       url: '/Controlador/Reporte,
                       beforeSend: function (jqXHR, settings) {
 
 //Esto es una acción que realiza la vista mientras se cargan le excel, en este caso yo use .BlockUI que es una librería javasrcript, pero puedes usar un div y una imagen como se ve en las líneas comentadas
                           //$('#loading').html('<img style="width: 140px;padding: 0px;margin: 0px;" src="./Img/ajax-loading.gif" alt="spinner" />');
                           //$.blockUI({ message: '<h1><img src="/Content/images/throbber.gif" /> Por favor espere...</h1>' });
 
                       },
                       data: {
                           Aca pasas tus parametros
 
 
                       },
                       success: function (data) {
                           
Aca desapareces la imagen que cargaste al principio

			//$('#loading').empty();
                           //$.unblockUI();
 
//Aca vamos a llamar la url que nos mostrara el archivo sin salirse de la página actual
                           window.location = '/Controlador/DownloadFile?fileGuid=' + data.FileGuid
                                             + '&filename=' + data.FileName;
                       },
 
 
                       error: function (jqXHR, textStatus, errorThrown) {
 
 
 
 
                       }
 
                   })

Finally in your controller you put the following code

    [HttpGet]
    public virtual ActionResult Download(string fileGuid, string fileName)
    {
        if (TempData[fileGuid] != null)
        {
            byte[] data = TempData[fileGuid] as byte[];
            return File(data, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName + ".xlsx");
        }
        else
        {

            return new EmptyResult();
        }
    }

It's a matter of adapting it to your components, it looks crazy but in reality it's very simple.

Greetings

    
answered by 23.11.2018 в 20:49