Retrieve file from database using an AJAX request in Model-View-Controller pattern

I'm having trouble implementing file download functionality through an ajax call in MVC. Every time I call the controller method, I keep getting a "parseerror". Can someone help explain why this is happening?

Here's my ajax code:

tab.on("click", ".FileDownload", function (e) {

    //$('#uploadStatus').html("ok");
    var tr = $(this).closest("tr");
    var id = tr.data("id");

    $.ajax({
        type: "POST",
        url: "/File/FileDownload",
        //contentType: false,
        //processData: false,
        //dataType: "json",
        data: { fileId: id },
        success: function (data) {
            $('#uploadStatus').html("ok");
        },
        error: function (err) {
            alert(err.statusText);
        }
    });

});

And here's the controller code:

[HttpPost]
    public FileResult FileDownload(int? fileId)
    {

        FileDBEntities db = new FileDBEntities();
        tblFile file = db.tblFiles.ToList().Find(p => p.id == fileId.Value);
        return File(file.Data, file.ContentType, file.Name);
    }

It works with a simple download link in Razor, but not with ajax. What am I doing wrong here?

Answer №1

Can't we simply utilize

tab.on("click", ".FileDownloadBtn", function (e) {

    //$('#uploadStatus').html("ok");
    var tableRow = $(this).closest("tr");
    var fileId = tableRow.data("fileId");

    window.location = window.location.origin + '/File/GetFile?fileId=' + fileId;

});

[HttpPost]
public ActionResult GetFile(int? fileId)

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

javascript has been overrunning with an abundance of attached comments loops

I've been encountering an issue where I am unable to properly link my comments to the message id. Below is what I have attempted: Routes file: router.get('/home', function(req, res){ if(req.cookies.user_id){ knex.raw(`SELECT * ...

useEffect was passed an additional argument in this current render cycle

Unable to Resolve Warning Message: A warning message is popping up stating: useEffect received a final argument during this render, but not during the previous render. Even though the final argument is optional, its type cannot change between renders. h ...

Troubleshoot the Error: EEXIST - Directory already exists at 'C:UsersPhantom' while setting up a React application[RESOLVE]

I'm trying to set up react and start my first project, but I encountered an issue during the installation process. How can I resolve this? Error: EEXIST: file already exists, mkdir 'C:\Users\Phantom' TypeError: Cannot read propert ...

Is there a different method in lodash that can be used instead of _.merge.apply(_, array); when the array contains multiple objects?

Is there a way to combine all the properties from multiple objects in an array into a single object using lodash without using apply or iterating through the array? const arr = [{1:1, 2:2}, {3:3}, {4:4}]; _.merge({}, ...arr); // {1:1, 2:2, 3:3, 4:4}; ...

sending arguments to a function within ng-show

How can I properly call a function with a parameter in ng-show without errors? I encountered the error Error: [$parse:syntax] Syntax Error: Token ']' not a primary expression at column 8 of the expression [cheked[]] starting at []]. The parameter ...

According to Intelijj IDEA, the success function in the AJAX request is reported as unused

I've encountered an issue and I'm unsure of the cause. This is my code for testing AJAX requests: function sendAJAX() { var dataToSend = {}; dataToSend["username"] = $("#username").val(); dataToSend["age"] = $("#age").val(); data ...

Issue of Promise Rejection encountered while attempting to retrieve video URL through discord.js and utilizing the Youtube API

Exploring Promises with Youtube API Requests I am currently working on a music function for my Discord bot in discord.js. I have successfully tested the function with a fixed video URL, but now I want to add support for user input using the YouTube API. H ...

Tips for persisting an entity in Entity Framework with a column that has a database-generated value

One of the challenges I'm facing is automating the creation of an ID in my controller without hardcoding it. The webpage in my project allows users to sign up with their information, which is then sent to the controller via an API call from the fronte ...

Encountering the error message "ReferenceError: parsePayload cannot be accessed before initialization"

Check out this code snippet: Experiencing an issue with 'ReferenceError: Cannot access 'parsePayload' before initialization' Any assistance would be appreciated const express = require("express"); const { createToDo, updateToD ...

Error message: 'query is not a valid function' when using Next.js getServerSideProps with Firebase

I am currently developing an app for an NGO using NextJS and firebase as the primary database. While working on my project, I encountered a concerning issue. import { collection, where, query, getDocs } from '@firebase/firestore'; import ...

Is there a maximum file size limit for uploads in jQuery when using ajax requests?

I'm curious if there's a size limit for jQuery uploading (via Ajax)? Specifically, I'm working on a form to upload multiple images to the server (currently using WampServer locally). So far, I've been able to easily upload one, two, or ...

An API built with Mongoose, Express, and Node.js is currently only able to send a single image

I have a buffer array that needs to be converted into images and sent to the user. The issue is that the current code only sends one image: const express = require("express"); const asyncHandler = require("express-async-handler"); const ...

Create a more concise JavaScript function for updating MongoDB using if/else statements

Can this function be optimized for efficiency and readability? I'm not a fan of the repetitive if/else structure, especially considering that it's only setting 'status.edited': false when method equals 'reset'. Otherwise, it s ...

Displaying data on a monthly basis along the X-axis in Recharts

I need the X Axis to only display the months, while still being able to add content on different days within each month. My attempts to use ticks resulted in the removal of the X Axis. I then tried using ticksFormatter, but it caused the X Axis captions t ...

"Triggering a function with an onclick event when receiving Ajax

Hey there, I'm in the process of using Ajax to retrieve a SELECT tag. Essentially, when I click a button, it will insert a SELECT tag within the HTML. Each option within the select tag will have different outputs. I'm currently struggling to get ...

Enable submitting data to static files on the ASP.net development server

Encountering an issue where a service needs to POST to the root of my ASP.net application running in my Visual Studio development instance (/myapp/ for example). Unfortunately, ASP.net is throwing an error stating that "The HTTP verb POST used to access pa ...

What is the best method to update values from a JSON file that has been read?

Trying my hand at modifying values in a JSON file without changing one particular value. Below is the code I've come up with, but to provide more context, I'll add some filler text so you can skim through and analyze the code. Don't be too h ...

Developing a JSON structure that is able to be deserialized within a C# environment

While attempting to generate a JSON object that can be interpreted as a C# object, I continually encounter 400 bad request errors when sending it via AJAX. Here's my JavaScript snippet: $.ajax({ type: "POST", url: "LeagueService.svc/Fixtures ...

Strange jQuery Bug

Previously, the code on my website was functioning correctly: $("#usr").load("somepage.php",{var1:var1,var2:var2}); However, after making changes to the navigation bar code, jQuery started behaving oddly. The first issue that arose was with this line: v ...

Efficiently inserting data into various tables within a typed dataset

Allow me to simplify my issue as much as possible. Feel free to provide feedback and correct any errors in my English. I hope my message is clear. My primary question is: Is there a simple and "automated" method to populate a dataset table with rows that ...