Issue with FileStreamResult not triggering download prompt after AJAX call in MVC

I am encountering an issue with my code that is triggered by the "export" li tag. It converts a FusionChart to an SVG string and then sends it to my controller via an ajax call.

The problem I'm facing is that even though the controller receives the request, processes it successfully till the end, and displays "Success" in an alert message, the popup to save the PDF does not appear.

Interestingly, when I copy the entire HTML string, paste it into notepad, save it as an HTML file, everything works as expected. However, it fails to function properly when running from the controller and trying to display the save prompt...

Could there be something I'm overlooking? Or perhaps I'm doing something incorrectly or not following best practices?

Here's the section of code that invokes a JavaScript function:

<li id="export" style="font-size:13px"><a onclick="svgString()">Rotativa Export</a></li>

Below is the JavaScript code responsible for making the AJAX call:

function svgString() {
    var ChartSVG = new Array(10);
    var text = document.createTextNode(savingsChart.getSVGString());
    document.getElementById("msg").appendChild(text);

    ChartSVG = chunkSubstr(document.getElementById("msg").innerHTML, 10);

    var Details = {
        "fkiProjectID": @Model.fkiProjectID,
        "ChartSVG": ChartSVG
    };

    $.ajax({
        url: '/Profile/ExportCombinedPDF',
        data: JSON.stringify(Details),
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        success: function(data) {
            alert("Success : " + data);
        },
        error: function(data) {
            alert("Error: " + data);
        }
    });
}

document.getElementById("export").addEventListener("click", svgString);

function chunkSubstr(str, size) {
    var numChunks = Math.ceil(str.length / size),
        chunks = new Array(size);

    for (var i = 0, o = 0; i < size; ++i, o += numChunks) {
        chunks[i] = str.substring(o, o + numChunks);
    }

    return chunks;
}

Controller:

public FileStreamResult ExportCombinedPDF(CalculatedOutputViewModel CVM) {
    // Controller logic goes here...
}

If anyone can provide insight or assistance on this matter, it would be greatly appreciated! Thank you!

Answer №1

delete the following code

using (var input = new MemoryStream(bytes))
{
      // The 'using' statement disposes of the stream before returning      
}

replace it with this

 var input = new MemoryStream(bytes);

Answer №2

After some tweaking, I managed to figure this out. It required adjusting my approach slightly, but in the end, it all came together perfectly.

This is what I ended up doing :

  1. I clicked on a button that triggered my JavaScript Function, which then made an ajax call to display a partial view as a modal. The modal would only open once the ajax call was complete.
  2. Within this partial view, there was a "print" button. When clicked, I submitted the Model back to my controller and constructed the necessary string within the action result.
  3. I utilized Rotativa ViewAsPdf to prompt the save dialog with the desired content displayed.

While it wasn't exactly how I envisioned it, the outcome matched my initial goal perfectly.

Below is the code snippet :

View:

This section contains the Modal along with the corresponding button:

<div class="modal fade" id="PrintModel" tabindex="-1" role="dialog" aria-labelledby="myPrintModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
            </div>
            <div class="modal-body">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default3" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<div>
    <button id="get" data-loading-text="Preparing..." type="button" class="btn btn-default2" data-dismiss="modal">Prepare for Print</button>
</div>

Javascript snippet (including the FusionChart part):

FusionCharts.ready(function () {
    var savingsChart = new FusionCharts({
        id: 'chart-1',
        type: "scatter",
        renderAt: "chart-container",
        width: "1000",
        height: "500"
    });
    ...

Controller

public ActionResult PrepareForPrint(CalculatedOutputViewModel model)
        {
            CalculatedOutputViewModel CVM = new CalculatedOutputViewModel();
            ...
        }

        public string ExportCombinedPDF(CalculatedOutputViewModel CVM)
        {
            List<PipelineDetails> PipeList = new List<PipelineDetails>();
            ProjectManager PM = new ProjectManager();
            ...
        }
...

Partial View

@model AirFlo_Size_Programme.Models.CalculatedOutputViewModel
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
...

Although not perfect, this solution did the trick. Hopefully, this can be helpful to others experiencing similar challenges.

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

Using webpack to bundle node_modules into your application

I am facing an issue while trying to load some modules like: moment echarts In my package.json file, I have the following versions specified: "echarts": "^3.1.10" "moment": "^2.14.1" However, I am encountering the errors below: VM2282:1 Uncaught Ref ...

What is the recommended element for managing data in React?

Let's consider a scenario where we have 2 main components: class App extends React.Component { state = { comments: [1, 2, 3, 4] } render() { return ( <Comments /> ) } } class Comments extends React.Component { rende ...

Can you explain the distinction between using "require" to return a module and accessing the actual object in node.js?

When working with node.js, the commonly used method to include modules from other files is by using "require", whether it's from our own code or third-party libraries. But for me, there seems to be some confusion regarding the distinction between the ...

The datepicker UI triggers the onChangeMonthYear event before executing the beforeShowDay function

I am currently using the jQuery Datepicker UI (http://jqueryui.com/datepicker/) My goal is to dynamically color specific days based on data retrieved from an AJAX call. This is the current setup: $(document).ready(function() { getAllDays(); $("# ...

Is it possible to utilize PDF.js once the PDF file has been downloaded?

My goal is to integrate PDF.js (or Viewer.js) with a Flask application, where I have already retrieved the file from a server. Instead of using PDFJS.getDocument('helloworld.pdf') I prefer to display the downloaded PDF in the browser through a ...

What's the best approach for revalidating data with mutate in SWR?

Whenever a new album is created in my app, the post request response includes an updated list of all albums. To enhance the user experience, I wanted the newly created content to automatically show up without requiring a page refresh. Although I am famil ...

Re-Rendering Component in React Continuously Keeps Checkbox Checked Event Flowing

I am working on a material ui checkbox formgroup that is generated dynamically based on data received from an API. Essentially, the user is presented with a question and a set of answers. The user checks all the valid answers and clicks 'next'. I ...

`The value of an element within an array changes automatically`

In my current setup, I have a traditional array where each element represents an HTML element. The issue arises when I manipulate these elements within the array; any changes made to the HTML element also reflect in the array automatically. However, I pref ...

Nested Elements in Java JSON with Jackson

I have a JSON string that contains nested values. It looks something like this: "[{"listed_count":1720,"status":{"retweet_count":78}}]" I am interested in extracting the value of retweet_count. Currently, I am using Jackson to work with this data. The ...

Encountered difficulty parsing json data using cUrl in a PHP script

This is my first time encountering a web service. The JSON data from the .NET server is received and encoded to base64 by the PHP server. The issue I am facing currently is the inability to access each attribute within the data: Array ( [JSONDataResult] ...

Retrieving nested JSON objects in Node.js using Express and Postgres through iterative queries

I've been experimenting with this code in Node.js using Postgres to retrieve a list of nested JSON objects like the one shown below: { "elements": [ { "name": "element 1", "description": "lorem ipsus", ...

How to utilize Unity's JsonUtility with a class that includes arrays

In Unity, I am currently working on developing a game that utilizes Tilemaps to procedurally generate a world in a similar fashion to a 2D Minecraft setup. The game consists of two main classes: Chunk, which represents a 16x16 integer array containing tile ...

Automatically updating quantity with the power of jQuery

I have created a spreadsheet where users can input their expenses and the total will update automatically. Initially, I have set some default numbers in my HTML which are editable for users to modify as needed. However, I am facing an issue with my JQuer ...

What causes let to lose significance within the context of React development?

In my React code snippet, I am encountering an issue with the organizationId variable. Even though I can see its value in the first and second instances, I am unable to see it in the third instance. This strange behavior is occurring in a Next.js based pro ...

I need the title to be filled with the input data and the content to be filled with the textarea data

import React from 'react'; export default class CreateNote extend React.component { constructor(props) { super(props); this.state = {note:{title:" ",content:" "} }; console.log(this.state); ...

ASP.NET - Severely struggling with connectivity issues involving AJAX/JQUERY

I have developed a real-time update script that refreshes certain div elements with server-side information every second. The issue I am facing is that the script seems to be causing heavy usage, as even my mouse animation in Google Chrome keeps loading. ...

Update the content within a div based on the selected option from a dropdown menu or

Is there a way to change the displayed text based on user input or selected option? By default, the text shown is "Aa Bb Cc Dd Ee...", but it can be changed by selecting different options. If text is typed into the input field, the displayed text will up ...

Calculate the total sum of a specific property within an array using ES6

My goal is to calculate the total unit value by date and create a new array without duplicate dates. For instance, I want to sum up the values of 2015-12-04 00:01:00. This particular date appears twice in the dataset with values of 5 and 6, resulting in: ...

Utilizing AJAX and Hibernate for a seamless login experience

Creating a login form that is connected to a database has been challenging for me. When a user enters an incorrect username, I want AJAX to respond with "wrong username". My servlet is integrated with Hibernate, allowing me to check usernames against the d ...

Guide to configuring the API key within the Stampery API.JS script

Currently, I'm in the process of configuring Stampery but I'm facing difficulty locating where to insert the string API key within the API.JS file. The documentation mentions setting the STAMPERY_TOKEN as the API key, but I'm unsure how to p ...