Sending table data with files or input string data to the server in .NET ASPX web forms is not allowed

When the add button is clicked, the product type, name, and file are added to the table.

The variables are declared globally.

document.getElementById("addBtn").addEventListener("click", function () {
    var entryExists = false;
    var documentName = document.getElementById("chooseFileInput");
    var productNameValue = productNameDropdown.value;
    var file = documentName.files[0];

    var entryforTable = {
        product_Type: productTypeValue,
        product_Name: productNameValue,
        document_Name: file
    };

    var dataTable = document.getElementById("dataTable").getElementsByTagName('tbody')[0];
    var row = dataTable.insertRow(-1);
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    var cell3 = row.insertCell(2);
    var deleteCell = row.insertCell(3);

    var deleteButton = document.createElement("button");
    deleteButton.textContent = "Clear";
    deleteButton.className = "btn btn-danger";
    deleteButton.addEventListener("click", function () {
        dataTable.removeChild(row);
        var index = tableData.indexOf(entryforTable);
        if (index > -1) {
            tableData.splice(index, 1);
        }
    });
    deleteCell.appendChild(deleteButton);

    cell1.innerHTML = entryforTable.product_Type;
    cell2.innerHTML = entryforTable.product_Name;
    cell3.innerHTML = file.name;

    tableData.push(entryforTable);
    productType.value = "";
    productNameDropdown.value = "";
    documentName.value = "";
});

When the submit button is clicked, the data is sent to the server.

document.getElementById("submitBtn").addEventListener("click", function () {
    var formData = new FormData();

    console.log(tableData);
    tableData.forEach(function (entry) {
        formData.append('productTypes[]', entry.product_Type);
        formData.append('productNames[]', entry.product_Name);
        formData.append('files[]', entry.document_Name);
    });

    console.log(formData);

    fetch("ThirdPartyProductDocsUpload.aspx/SaveFiles", {
        method: "POST",
        body: formData
    })
        .then(response => {
            console.log(response);
            if (response.ok) {
                return response.json();
            }
            throw new Error('Network response was not ok.');
        })
        .then(data => {
            console.log("Response from server: " + data);
        })
        .catch(error => {
            console.log("Error: " + error);
        });
});

The debugger set on this function does not get hit, but the response from JavaScript is incorrect.

[WebMethod]
public static string SaveFiles(string jsonData)
{
    try
    {
        // Deserialize the JSON data into an array of objects
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        Entry[] entries = serializer.Deserialize<Entry[]>(jsonData);

        // Validate input
        foreach (Entry entry in entries)
        {
            if (string.IsNullOrEmpty(entry.Product_Type) || string.IsNullOrEmpty(entry.Product_Name) || entry.Document_Name == null)
            {
                throw new ArgumentException("Invalid input parameters.");
            }

            // Save the file
            string fileName = Path.GetFileName(entry.Document_Name.FileName);
            string uploadPath = HttpContext.Current.Server.MapPath("~/TPPUploadFiles/");
            string filePath = Path.Combine(uploadPath, fileName);
            entry.Document_Name.SaveAs(filePath);

            // Additional processing if needed
        }

        return "Files uploaded successfully.";
    }
    catch (Exception ex)
    {
        return "Error: " + ex.Message;
    }
}

The goal is to send the table data to the backend to save the files and product names.

Answer №1

Consider using this approach:

JSON.stringify(formData);

Then, submit it in this manner:

fetch("ThirdPartyProductDocsUpload.aspx/SaveFiles", {
        method: "POST",
        data: {
             jsonData: JSON.stringify(formData)
         }
    })

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

Implement a fadeout effect by using a timeout function that adds a class to the div element in

I implemented a loader on my webpage that animates for 3 seconds before a function kicks in to modify the styles and make it invisible. I am looking to add a fadeout effect when the 'waa' style is applied to the 'load' div. setTimeou ...

Tips for linking server value with Javascript onmousedown in an aspx web page

I have a single Hyperlink on an aspx page. There are two tasks I need to accomplish: When I click on the hyperlink, I want to log some activity. While logging the EmployeeID value, I need to bind it from the server. However, I am encountering an error t ...

The asynchronous callbacks or promises executing independently of protractor/webdriver's knowledge

Could a log like this actually exist? 07-<...>.js ... Stacktrace: [31m[31mError: Failed expectation[31m [31m at [object Object].<anonymous> (...06-....js)[31m[31m[22m[39m It seems that something is failing in file -06- while I am processin ...

Modifying a Field's Value by Referring to a Different Field

I am working on developing a form that includes a dropdown menu for changing the aircraft type. Additionally, I want to incorporate another field named "Registrations" which will automatically update the available registration options based on the selected ...

The bundle.js file is displaying HTML code instead of JavaScript

I have been working on setting up redux server-side rendering using express.js. Most of the setup is done, but I encountered an error while trying to render the page in the browser. The error message Uncaught SyntaxError: Unexpected token < is appearin ...

Unable to fetch information from the local host using an AJAX request and PHP script

I'm having trouble retrieving the <p> elements echoed in my PHP script. I need a solution that allows me to style these <p> nodes using a JavaScript function without refreshing the page. Can someone help me with this issue? Here is my PHP ...

Implementing CKEditor instances within AngularJS Controller scopes

Greetings everyone, Recently, I have been exploring Angular JS. Everything is going smoothly - my controllers, services, and so on. However, when attempting to make a Div editable that is within the ng-controller, the ckeditor toolbar fails to appear. On ...

Uncertain entities in Typescript

I used to use Flow for typing. How can I type an imprecise object? Here's the array I'm working with: const arr = [ {label: 'Set', value: setNumber, id: 'setNumber', set: setSetNumber, type: 'text'}, ...

When Using TypeScript with Serverless, 'this' Becomes Undefined When Private Methods are Called from Public Methods

Currently, I am working on constructing an AWS Serverless function using TypeScript. My focus is on creating an abstract class with a single public method that invokes some private methods. Below is the simplified version of my TypeScript class: export ...

Having issues with Angular Material, specifically with mat-list-item and routerLinkActive not functioning as expected

Currently, I am working with a navigation view that utilizes the MatSidenavModule. The issue I am encountering is on mobile screens. When I click a mat-list-item, the mat-sidenav closes as expected. However, upon opening the mat-sidenav again, Material alw ...

Navigating through a JSON object in JavaScript by employing regular expressions

Is there a way to extract the "Value" of elements "Data1", "Data2", "Data3", "Data4" from a JSON object without resorting to regex? I've heard that using regex with JSON is not recommended. <script> abc = { "model": { ... } } </script> ...

What are the steps to address the Invalid Hook Call issue while working with Material UI?

Having an issue with a MaterialUI Icon in my code as a newcomer to coding. Here is the snippet: import PersonIcon from '@mui/icons-material/Person'; function Header() { return ( <div> <PersonIcon /> <h2>Header file</h2 ...

Disable the toggling of the dropdown functionality in the bootstrap function

Recently, I made some modifications to a bootstrap navbar by transforming it into a toolbar and adjusting a dropup dropdown to include two datepicker elements. An issue arose when the dropdown would collapse upon selecting a date. To address this problem, ...

Learn how to dynamically switch the background image of a webpage using a button in AngularJS

Hey there, I'm currently working on incorporating interactive buttons into my website to give users the ability to customize the background. I've been experimenting with Angular to achieve this feature. So far, I've managed to change the ba ...

Is there a way to acquire and set up a JS-file (excluding NPM package) directly through an NPM URL?

Is it feasible to include the URL for the "checkout.js" JavaScript file in the package.json file, rather than directly adding it to the Index.html? Please note that this is a standalone JavaScript file and not an NPM package. The purpose behind this appr ...

Ways to eliminate or conceal solely the play/pause symbol or button from the media player within the video tag

[Please see the screenshot attached, I am looking to remove the play/pause icon that is highlighted] [screenshot] How can I hide or remove only the play/pause button from the media player of a video tag? When I dynamically add the controls attribute using ...

Is there a way for me to set distinct values for the input box using my color picker?

I have two different input boxes with unique ids and two different color picker palettes. My goal is to allow the user to select a color from each palette and have that color display in the corresponding input box. Currently, this functionality is partiall ...

Storing multilingual JSON data in AngularJS for faster access

I have successfully implemented a multi-language concept in my application, but I am facing an issue where the language (.json) file is being loaded for every field. As a result, the application takes a longer time to load. My requirement is to load the .j ...

Error message for Joi when validating a nested array of objects

I have received user input from the client side and am performing backend validation using Joi. const Joi = require("joi") const schema = Joi.array().items( Joi.object().required().keys({ name: 'filter_list', value: Joi.array(). ...

Enhancing the appearance of a checkbox within a ReactJS setting

I'm having trouble customizing a checkbox in a ReactJS environment for IE11. I've tried various approaches, but nothing seems to work. Can anyone offer any advice? Here is the code snippet: CSS: .squared { input[type=checkbox] { bo ...