Troubleshooting Problems with File Upload Response in ASP.Net MVC Ajax.BeginForm

I have implemented a modal feature that allows users to upload a file. I am looking for a JSON response to indicate whether the upload was successful or not, and then display this information to the end user.

Here is my current View:

@model int

<div id="modal_newSupportPlan" class="modal fade" style="display:none;">
<div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header bg-primary">
            <button type="button" class="close" data-dismiss="modal">x</button>
            <h6 class="modal-title">New Support Plan</h6>
        </div>
        @using (Ajax.BeginForm("CreateSupportPlan", "Client",
            new AjaxOptions() { OnSuccess = "getSupportPlanResult", HttpMethod = "post" },
            new { @Class = "form-horizontal", enctype = "multipart/form-data" }))
        {
            <div class="modal-body">
                <input name="ClientFK" value="@Model" style="display:none" />
                <div class="form-group" id="newsupportplan_error_plantype">
                    <label class="control-label col-sm-3">Type of Plan</label>
                    <div class="col-sm-9">
                        <select id="planType" name="PlanType" class="form-control">
                            <option></option>
                            <option value="1">Initial Plan</option>
                            <option value="2">Pre Employment Plan</option>
                            <option value="3">6 Month Plan</option>
                            <option value="4">12 Month Plan</option>
                            <option value="5">Ongoing Support Plan</option>
                        </select>
                    </div>
                </div>
                <div class="form-group" id="newsupportplan_error_StartDate">
                    <label class="control-label col-sm-3">Date</label>
                    <div class="col-sm-9">
                        <input type="text" class="form-control pickadate-accessibility" name="Date" />
                    </div>
                </div>
                <div class="form-group" id="newsuportplan_error_SLILevel">
                    <label class="control-label col-sm-3">Support Level</label>
                    <div class="col-sm-9">
                        <select id="SliLevel" name="SliLevel" class="form-control">
                            <option></option>
                            <option value="1">SLI 1</option>
                            <option value="2">SLI 2</option>
                            <option value="3">SLI 3</option>
                        </select>
                    </div>
                </div>
                <div class="form-group">
                    <label class="control-label col-sm-3">Upload File</label>
                    <div class="col-sm-9">
                        <input type="file" name="Blob" />
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-link" data-dismiss="modal">Close</button>
                <button type="submit" class="btn btn-primary">Save</button>
            </div>
        }
    </div>
</div>

This is my Controller method:

[HttpPost]
    public ActionResult CreateSupportPlan(ModelHelper.SupportPlanViewModel supportPlanDetails)
    {
        try
        {
            esp_storage_supportPlans espStorageSupportPlans = new esp_storage_supportPlans();
            bool validation = true;
            var errorList = new List<string>();
            var passList = new List<string>();

            // Validation logic here...

            if (!validation)
            {
                return Json(new { result = "Validation", errors = errorList, pas s= passList }, JsonRequestBehavior.AllowGet);
            }

            return Json(new { result = "success" }, JsonRequestBehavior.AllowGet);
        }
        catch (Exception)
        {
            return Json(new { result = "failed" }, JsonRequestBehavior.AllowGet);
        }
    }

My JavaScript consists of two parts: the first part makes the form work by uploading the file, while the second part handles the success function:

window.addEventListener("submit", function (e) {
    // First part of JavaScript code
}, true);

// Second part of JavaScript code
function getSupportPlanResult(data) {
    console.log("here");
    if (data.result === "success") {
        // Success message handling here...
    } else {
        // Error message handling here...
    }
}

Answer №1

Have you ever considered utilizing a library like axios to streamline the process of handling XHR requests? It could greatly simplify your code, for example:

window.addEventListener("submit", e => {
    const form = e.target;
    if (form.getAttribute("id") === '<my_unique_id_of_this_element>') {
        axios({
           method: form.method,
           url: form.action,
           data: /* additional payload as needed */
        })
        .then(({data}) => getSupportPlanResult(data));               
    }
});

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

What steps should be taken to manage expired sessions with the combination of spring-security and jQuery?

In my application, I am utilizing spring-security and jQuery. The main page loads content dynamically into tabs through Ajax. Everything seems to be functioning correctly, but occasionally the login page pops up inside one of the tabs. When I enter my cred ...

What is the best way for me to send a confirmation response to my API once a user has clicked on the activation link

I have been attempting to send a confirmation message to my API after clicking on the activation link, but despite numerous attempts, I have not been successful. Please see the activation link below: <script type="text/javascript> ...

Exploring the use of analog clocks in C# Windows Forms applications

I'm looking to implement an analog clock on my Windows Form menu page using C#. I've created a user control called "AnalogControl" which utilizes a timer. Below is the code for the control: // Code for the AnalogClock user control [...] After ...

Transfer an HTML file object between two <input type="file"> elements

I am looking to integrate a multi-file uploader into a form that allows users to prioritize the files they upload using draggable and sortable jQuery tools. One way I have added a multi-file input is: <input type = "file" multiple> When I select m ...

Troubleshooting Areas in Asp.net MVC Layout for Routing Issues

Having an issue with MVC routing (or at least suspect it's related to MVC routing)... Here's how my workflow looks: In my project, I need to implement user-specific logins that are completely customized. To achieve this, I inserted my menu bar ...

AJAX request experiences significant delays due to MySQL query execution

The issue There is a significant delay in the execution of AJAX requests that involve any database queries. This problem has suddenly emerged without any recent updates to the codebase. Interestingly, if the same query is executed on a webpage directly (e ...

Restricting character count when displaying output in JavaScript

Is there a way to restrict the number of characters displayed on a label using a JavaScript file? I am encountering an issue with a specific part of the code that is triggered by a button click and is responsible for printing the contents from a preview bo ...

Angular 5 is throwing an error that says: "There is a TypeError and it cannot read the property 'nativeElement' because it

Being aware that I may not be the first to inquire about this issue, I find myself working on an Angular 5 application where I need to programmatically open an accordion. Everything seems to function as expected in stackblitz, but unfortunately, I am enco ...

Can you demonstrate how to convert a string date array into a JavaScript array?

I am facing a challenge where I need to convert a string representation of an array into a JavaScript array for the purpose of looping. The string in question is enclosed within single quotes. Inside my JavaScript code, I have the following: var length1 ...

Use jQuery to trigger a click event when an element is in focus, unless it was clicked to

I am currently developing a website using the MDL framework. One issue I encountered is that there is no default select form element provided. After some research, I found a solution by utilizing a menu component that displays when the input is clicked. Th ...

The function os.platform in React and Electron mistakenly identifies the browser as the operating system instead of the actual OS

In my quest to locate the appdata folder for the application, I encountered a challenge where each operating system has a different path for the appdata or application support folder. To address this, I attempted to identify the OS type in order to deter ...

The contents of the div do not display when the button is pressed except in jsfiddle

I have written a script that triggers the appearance of a div where users can adjust the time settings for a timer. The functionality works perfectly on JSFiddle, with the div displaying as intended. However, when tested on other online IDEs such as Coding ...

Something seems off with the color of the getImageData when using Fabric JS getContext('2d')

Website: Currently, I am working on adding an eye dropper feature to my website. It functions perfectly at a resolution of 1080p, but when tested on higher or lower resolutions, it malfunctions. Here is the basic code snippet: var ctx = canvas.getContex ...

What could be causing the issue with the initialization of useState not working as expected?

I have the following React code snippet: import React, { useState, useEffect } from "react"; import axios from "axios"; function App() { const [players, setPlayers] = useState([]); // Fetch all Players const getAllPlayersUrl = & ...

Exploring the world of JMeter: capturing sessions with JavaScript and jQuery

I need to capture a user session in order to conduct a performance test. I have been using the JMeter HTTP(S) Test Script Recorder, but unfortunately it is not recognizing javascript and jquery. The error message I'm receiving is: JQuery is not def ...

Using C# to parse JSON data and assign it to local variables

Here is a snippet of my code: public class MyClass_T { public string name; public string file_name_txt; public int version = 1; public double X; public double Y; ....and many more variables } I have saved the data to a JSON file ...

What is the reason that setTimeout does not delay calling a function?

I am looking to develop a straightforward game where a div is duplicated recursively after a short interval. Each new div should have a unique ID (ID+i). The concept is to continuously generate divs that the user must click on to remove before reaching a ...

Selenium WebDriver test for an Oracle ADF Task Flow application is failing on Internet Explorer 11

While I have successfully run a Selenium WebDriver test on Firefox and Chrome, the same test surprisingly fails on Internet Explorer 11. Upon investigation, it seems that the issue stems from using AJAX, as IE does not update the DOM Tree properly after an ...

Tips for troubleshooting AJAX (PHP) code that executes SQL queries

There's a small PHP file in my possession that carries out SQL INSERT and DELETE operations for an image tagging system. While most of the time these operations are successful, occasionally the insertions fail to work properly. I'm wondering if ...

Having an issue where I receive the error message "this.cancelOrderFunction is not a function" when trying to execute a method within a child component in Vue.js

I'm facing an issue while trying to execute a method that changes the text content of the currentStatus variable when the Confirm Cancel button is clicked. The button is located in the child component within a dialog box, while the method is supposed ...