Having trouble accessing a CSV file with JQuery and FileContentResult?

How can I make an ajax call without using ActionLink in my controller? Here is a snippet of my controller code:

public IActionResult ExportUsers(List<string> listOfEmails)
{
     /*some data processing*/
     return File(result, "text/csv", "ExportCandidates.csv");
}

When making the ajax call on the other side, I use the following method:

        $.ajax({
            url: '/Admin/Testcenter/GenerateInvitationPreview',
            type: 'post',
            data: {
                    //some input data to send to the controller   ​
           ​},
           ​success: function (response) {
               ​)
           ​}
       ​});

I have seen examples for PDF files where a base64 file is returned and handled in the ajax response. Is there a way to do something similar for CSV files so that the user can download it?

Answer №1

Utilize NPOI Library to Create Excel Sheets  

  //Generating Excel Sheet
        try
                {
                    Guid gid = Guid.NewGuid();
                    string ext = ".xls";
                    string[] Headers = { "Appointment ID", "Date of Appointment", "Doctor's Name", "Patient's Name", "Visit Type", "Status" };
                    string fileName = "AppointmentsExcelSheet_" + gid.ToString() + ext;
                    var serverpath = _env.ContentRootPath;
                    string rootpath = serverpath + "/wwwroot/ExcelSheets/" + fileName;
                    FileInfo file = new FileInfo(Path.Combine(rootpath, fileName));
                    var memorystream = new MemoryStream();
                    using (var fs = new FileStream(rootpath, FileMode.Create, FileAccess.Write))
                    {
    
                        IWorkbook workbook = new XSSFWorkbook();
                        ISheet excelSheet = workbook.CreateSheet("List of Appointments");
                        IRow row = excelSheet.CreateRow(0);
                        var font = workbook.CreateFont();
                        font.FontHeightInPoints = 11;
                        font.FontName = "Calibri";
                        font.Boldweight = (short)FontBoldWeight.Bold;
                        for (var i = 0; i < Headers.Length; i++)
                        {
                            var cell = row.CreateCell(i);
                            cell.SetCellValue(Headers[i]);
                            cell.CellStyle = workbook.CreateCellStyle();
                            cell.CellStyle.SetFont(font);
                        }
    
                        var result = _Appointment.GetAppoinmentsPDf();
                        int index = 1;
                        foreach (var app in result.Items)
                        {
                            //var PatientDob = Convert.ToDouble(app.PatientDOB);
                            row = excelSheet.CreateRow(index);
                            row.CreateCell(0).SetCellValue(app.AppointmentId);
                            row.CreateCell(1).SetCellValue(app.DateofAppointment+" "+app.TimeofAppointment);
                            row.CreateCell(2).SetCellValue(app.DoctorFullName);
                            row.CreateCell(3).SetCellValue(app.SelectedPatientName);
                            row.CreateCell(4).SetCellValue(app.PurposeofVisit);
                            if (app.IsActive == false)
                            {
                                row.CreateCell(5).SetCellValue("Inactive");
                            }
                            else
                            {
                                row.CreateCell(5).SetCellValue("Active");
                            }
                            index++;
                        }
                        workbook.Write(fs);
                    }
                    using (var filestream = new FileStream(rootpath, FileMode.Open))
                    {
                        filestream.CopyToAsync(memorystream);
                    }
                    memorystream.Position = 0;
                    //pass filepath to jQuery function
                    response.Msg = "/ExcelSheets/" + fileName;
    
                }
                catch (Exception Ex)
                {
                  //handle exceptions here
                }
           return Ok(reponse.Msg)
    //Implementing JavaScript
    function GenerateAppointmentsExcelSheet() {
        //var token = Token;
        //var link = path;
        debugger
        $.ajax({
            //'Content-Type': 'application/pdf.',
            type: "GET",
            url: "/api/Appointments/GenerateAppointmentsExcelSheet",
            beforeSend: function () {
                $.blockUI({
                    message: ('<img src="/images/FadingLines.gif"/>'),
                    css: {
                        backgroundColor: 'none',
                        border: '0',
                        'z-index': 'auto'
                    }
                });
            },
            complete: function () {
                $.unblockUI();
            },
           
            success: function (data) {
                debugger
                //download the Excel sheet
                window.location.href = data.msg;
                
            }
    
        });
    
    }

Answer №2

To achieve your desired outcome, it is recommended to avoid using AJAX and instead opt for a link click that triggers a new window to open (especially when passing parameters). Another option could be to utilize a form with a target="_blank" attribute to facilitate the response process. Within this form, you can include a single field or multiple input fields with the same name to store the list of emails. Your action handler would then be able to extract and manipulate this list before returning a File response. By submitting the form, the new window will automatically display the file generated from the operation.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Understanding ReactJs component syntax: Exploring the nuances and distinctions

Currently diving into the world of Reactjs and working on creating a basic component. I'm puzzled about why this particular syntax for a component: import React, { Component } from 'react'; export default class AboutPage extends Component { ...

Redirecting script upon successful connection detection

I have created a script that checks for internet connectivity using an image, and redirects if internet is available. However, the issue is that it caches the images, leading to attempts to load them even when offline. Is there a different approach I can ...

Creating PDF documentation in a JavaScript architecture MVC framework, specifically utilizing Backbone.js

In my project, I have implemented a Backbone Marionette single page application that interacts with a RESTful API backend using RoR. I am interested in providing users with the ability to export a PDF report that includes specific rendered views, regions, ...

React JS server conditional response malfunctioning

I've been facing issues with receiving a conditional response from an Express server for a React application. Check out the server-side code below: app.get('/api/checklogin', (req, res) => { var val = req.session.user ? false : tru ...

Unlock the Power of Heroku: Leveraging Node.js to Share Environment Variables Across JavaScript Pages

Currently, I am following the 'getting started' guide on the Heroku webpage. As part of this process, I have cloned their tutorial repository and decided to add my own index.html and app.js files to the existing /public folder. The directory str ...

How to achieve a typewriter effect in React using JavaScript

I've been attempting to incorporate a typewriter effect into my website - at the moment, the animation is functioning but each letter appears twice (e.g. instead of reading "Welcome!" it displays "Wweellccoommee!!"). I suspect this is an asynchronous ...

Trouble with $sce in Angular.js causing limitations on passing desired content into my directive

I've successfully developed a directive that animates a PNG Sequence. Everything functions perfectly when I manually input the image url, but when attempting to pass a dynamic url, I encounter an error related to $sce disallowing it. Below is the cod ...

Unexpected appearance of a blue line in Material UI when the overflow attribute is included

For my React application, I've integrated Material-UI along with styled components. The strange thing is that when I use a Chrome browser to view the app, I encounter an issue that doesn't seem to happen in Firefox. The problem arises when I add ...

Fade-in loader with centered placement on the full page

As a newcomer to programming, I wanted to implement a loader that displays a centered loading animation when the page loads or refreshes. The animation should gray out and fade the entire page until it fully loads. I've managed to get everything else ...

How can I use JavaScript to create a drop-down menu that only appears after selecting the previous one?

<div class="row"> <div class="col-md-4"> <label for="selectCustomers">Customer Select</label> <select class="form-control pointer" name="tableCustomers" id=" ...

What steps do I need to take to begin posting on NodeJS?

I am having issues creating a sample API for restaurants using the POST method. Despite launching the API and testing it in Postman, I'm not seeing any results. router.js const express = require('express'); const restaurantController = requ ...

The packery's overlapping issue arises when using the layout method to add HTML elements through AJAX, causing it to malfunction

This Example is not functioning The link above illustrates the issue I am facing. After adding text in a span using ajax, the divs started to overlap. However, when adding text without using ajax, the layout method worked properly. Example works fine wit ...

Creating a Draft.js selection with a specified start and end point

Looking for a way to replace the last insertion in Draft.js For instance, Original string -> aaazzz After inserting 'bbb' in the middle -> aaabbbzzz Replace last insert with 'ccc' -> aaaccczzz Replace last insert with &apos ...

Interacting with PHP variables in JSON format

I've recently started using JSON to exchange data between pages, but I am facing a challenge that I can't seem to solve. Essentially, my issue lies in one page where I am utilizing jquery's getJSON method to retrieve JSON data from another ...

Does PHP/AJAX only function when an output is generated?

I am attempting to fetch the Wordpress blog header into a php file in order to use it for an AJAX call function. define('WP_USE_THEMES',false); echo 'Something'; require(explode("wp-content",realpath(dirname(__FILE__)))[0].'wp-b ...

Invoking a web service using jQuery remotely

This piece of code is causing issues for me when I try to host Data.ashx locally. Interestingly, it seems to work fine when I use the URL pointing to Data.ashx on my local machine. jQuery.ajax({ type : "GET", url: "http://aspspider.ws/ghadyAlham ...

Sending a POST request using Node.js Express: A step-by-step guide

Looking for help on sending a post request from node.js Express with data passing and retrieval. Preferably a straightforward method like cURL in PHP. Can anyone assist? ...

Using Typeof in an IF statement is successful, but attempting to use ELSE with the same

My goal is to create a JavaScript variable called str. In case the ID idofnet doesn't exist, I would like to prompt the user for a value to assign to str. However, if idofnet does exist, then I want to retrieve its value and assign it to str. This is ...

Issues with exporting data to Excel in WEB API are causing problems and need to

I am having some issues with exporting JQGrid data to Excel from my WEB API controller. I'm trying to handle it through a controller method and everything seems to be working fine, but the Excel file is not showing up properly. <input type="image" ...

How to handle non-ASCII characters when encoding in JSON?

I understand that json_encode requires UTF-8 encoding, and I have already ensured that my data is encoded as such. However, when attempting to pass a PHP array to JavaScript, I am encountering difficulties in transferring the data successfully. To test th ...