Steps to open a PDF from a Response MemoryStream in a new tab

I'm not entirely sure if this is the right approach. My goal is to display a PDF in a new browser tab.

I have a method that generates a MemoryStream and returns it to my ajax call. What is the best procedure for achieving this?

Here is my Ajax Call:

$("#selector").click(function () {
    urlToFunction = "/Controller/Function";
    $.ajax({
        url: urlToFunction,
        data: ({ id: 12345 }),
        type: 'GET',
        success: function (response) {
           ???? here
        },
        error:
            function (response) {
            }
    });   
});

[HttpGet]
public async Task Print(int? id)
{

    var ms = GETMemoryStreamPDF();

    Response.ContentType = "application/pdf; charset=utf-8";
    Response.Headers.Add("content-disposition", "attachment;filename=" + randomName + ".pdf;charset=utf-8'");
    await Response.Body.WriteAsync(ms.GetBuffer(), 0, ms.GetBuffer().Length);
}

My question lies here:

success: function (response) {
           ???? here
        },

What is the recommended practice for displaying my PDF in a new tab?

Answer №1

Below is a code snippet you can use:

Javascript

$("#selector").click(function (e) {
    e.preventDefault();
    window.open('@Url.Action("ActionName", "ControllerName", new { id=12345})', '_blank');
});

Controller

[HttpGet]
public IActionResult Pdf(int? id)
{
    MemoryStream memoryStream = new MemoryStream();

    PdfWriter pdfWriter = new PdfWriter(memoryStream);

    PdfDocument pdfDocument = new PdfDocument(pdfWriter);

    Document document = new Document(pdfDocument);
    document.Add(new Paragraph("Welcome"));
    document.Close();

    byte[] file = memoryStream.ToArray();
    MemoryStream ms = new MemoryStream();
    ms.Write(file, 0, file.Length);
    ms.Position = 0;

    return File(fileStream: ms, contentType: "application/pdf", fileDownloadName: "test_file_name" + ".pdf");
}

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

Leverage AJAX to transmit a PHP array to an external JavaScript file

I have a situation where I need to transfer an array from a PHP file to an external JavaScript file. My approach involves using AJAX as it appears to be the most suitable method for achieving this. However, when I try to use echo json_encode($exif), the JS ...

The Web Api has encountered an error with a 302 status code, indicating a failure in authentication. Along with this error, a

I've encountered a perplexing issue and can't seem to find a solution. My web API application works perfectly until it times out. At that point, when I make an AJAX call, the server responds with an empty response as well as an additional one con ...

JavaScript struggles when dealing with dynamically loaded tables

I am currently working on integrating the javascript widget from addtocalendar.com into my website. The code example provided by them is displayed below. Everything functions as expected when I place it on a regular page. However, I am facing an issue wher ...

Guide to updating a database using ajax and javascript in asp.net mvc without the need to refresh the page

Is there a way to update the value of an enumdropdownlist from "active" to "inactive" in my database through an ajax call without having to refresh the page? I am unsure whether to use a javascript method or ajax.beginform for this task. I attempted to us ...

Constructing and rendering PDFs with c# and React

I am currently working on a project involving the generation of a customized PDF file based on user input and database information. I am seeking guidance on executing this project and deciding on which frameworks to utilize. The project is divided into thr ...

javascript authorization for iframes

I am currently working on a localhost webpage (parent) that includes an iframe displaying content from another url (child; part of a different webapp also on localhost). My goal is to use JavaScript on the parent-page to inspect the contents of the iframe ...

Update the content of a div element with the data retrieved through an Ajax response

I am attempting to update the inner HTML of a div after a certain interval. I am receiving the correct response using Ajax, but I am struggling to replace the inner HTML of the selected element with the Ajax response. What could be wrong with my code? HTM ...

Exploring the differences between detecting the XMLHttpRequest object in JavaScript and using the try

When it comes to determining browser support for AJAX, I typically rely on object detection like this: if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else if (window.ActiveXObject) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } ...

The ajax success() function is failing to function properly when attempting to make a call

The button's onClick() event is not navigating anywhere. There seems to be an issue with the success() function of the ajax call. Unfortunately, I am new to this and unable to pinpoint the problem. var currentAuthor=""; var currentQuote=""; $(documen ...

Nested Ajax request fails and triggers a full page reload

My goal is to search for product information and images using a product code input on index.php. The query runs in open_first.php via an ajax post request, which works perfectly. open_first.php displays images that can be selected by clicking on them. How ...

Showing post response (XMLHttpRequest) on Chrome extension interface instead of Python console

I am currently developing a Chrome extension that sends a post request with information about the specific URL being browsed by the user to Flask (local host). A web scraping process is then carried out on this URL to determine a category based on the obta ...

Is there a way to send a variable to the alert function using $.ajax()?

I need assistance with confirming the deletion of a record. When the user clicks on the button, it should send the value 'Yes' to a $_POST request in PHP for deleting the record. However, instead of working as expected, it is showing me the JavaS ...

What is the best way to halt an asynchronous method as a user?

How can I implement a mechanism that allows a user to stop an async method in MVC? My idea for implementation is as follows: public string stopToken { get; set; } public int iteration { get; set; } public async Task<string> someActionAsync() { ...

Generating links within a popover using an array in Rails 4

Within my application, Users have the ability to recommend other Users' profiles seamlessly. The functionality related to models and associations is working perfectly, as I am able to identify which users have recommended the current_user's profi ...

Customized Error Handling Function for Ajax Requests

I have a function that works perfectly, but I need to add six more buttons without repeating code. I want each callback to be customizable, with different text for each scenario (e.g. displaying "Please Log In" if the user is not an admin). How can I make ...

Troubleshooting the malfunction of jQuery's change() function

There are three HTML select tags on my page. I want these three select tags to function as follows: When I change selectA, selectB should automatically update based on the selection in selectA. Similarly, when an option in selectB is created, changing se ...

Is there a way to configure Gmail to automatically send me an HTTP request whenever I receive a new message?

I am developing a Laravel application to efficiently manage my Gmail account using the Google Client API for seamless customer connection with employees. Within my app, there is a "last_interaction" attribute assigned to each client that automatically upd ...

IE10 does not support Ajax functionality

I am facing an issue with a demo that uses jQuery AJAX post. The demo works fine on Chrome and Firefox, but it does not work on IE10. You can view the demo here. I would appreciate any help in resolving this problem. Thank you for your assistance. Here is ...

Issue encountered on IIS 7.x server during deployment with HTTPS

Currently, I am running an Angular + .Net 4.5 fullStack application on IIS V7.5 with Windows Server. To conduct additional tests, I am using multiple instances of the same site with different versions of the application deployed on the same host. Each inst ...

In the realm of asp.net, the OnClick event springs into action after the

My asp button uses OnClientClick to execute a javascript function, and I also want to run OnClick after OnClientClick. However, the OnClick never seems to execute. Despite looking through similar topics on StackOverflow and other websites, I can't see ...