Using AJAX for form submission while preventing default submission behavior and sending the selected file from a file control in C# –

In my project, there is a form that renders from a partial view. I am looking to send both the form data and the selected file from the file control using an ajax call for form submission. Below is the code snippet that saves the selected file to a folder:

Below is the JavaScript function:

<script type="text/javascript">
    $(function () {
        $('#careerForm').submit(function (e) {
            e.stopPropagation();
            e.preventDefault();

            var formData = new FormData();
            var totalFiles = document.getElementById("fuUploadCV").files.length;

            for (var i = 0; i < totalFiles; i++) {
                var file = document.getElementById("fuUploadCV").files[i];
                formData.append("FileUpload", file);
            }

            $.ajax({
                type: "POST",
                url: '/CareerSurface/UploadImage/', //put your controller/action here
                data: formData,
                dataType: 'json',
                contentType: false,
                processData: false,
                beforeSend: function (xhr) {
                    //do something before send
                },
                success: function (data) {
                    //do something if success
                },
                error: function (data) {
                    //do something if error
                }
            });
        });
    });
</script>

Here is the HTML:

using (Html.BeginForm("ApplyNow", "CareerSurface", FormMethod.Post, new { enctype = "multipart/form-data", autocomplete = "off", id ="careerForm" })){
    <div class="Field-Label-Box">
        <label>First Name:<span> *</span></label>
    </div>
    <div class="Field-Value-Box">
        @Html.TextBoxFor(model => model.FirstName, new {  id = "txtFirstName", name = "txtFirstName", required = "required" })
        @Html.ValidationMessageFor(model => model.FirstName)
    </div>
    ......
    <div class="Field-Label-Box">
        <label>Upload CV:<span> *</span></label>
    </div>
    <div class="Field-Value-Box">
        @Html.TextBoxFor(model => model.ResumeUpload, new { type = "file", id = "fuUploadCV", name = "fuUploadCV", required = "required" })</div>
    <input type="submit" id="btnSave" value="Submit" name="btnSave"  />

}

c# :

[HttpPost]
public void UploadImage()
{
    if (Request.Files.Count > 0)
    {
        dynamic file = Request.Files[0];
        //do something with your 'file'
    }
}

The current setup works well for sending only the selected file. However, I now need to also send all other data (model class object) to the same controller method. I have attempted using JSON but encountered an 'Illegal Invocation' error.

If you have any suggestions on how to pass both sets of data to the single method, please let me know. Feel free to ask if you have any questions. I appreciate any help as I am currently stuck at this point.

Thank you.

Answer №1

After reviewing your code, it appears that the only missing piece is adding additional fields to the FormData object being sent via AJAX. To rectify this, you should update your JavaScript as follows:

var formData = new FormData();
var totalFiles = document.getElementById("fuUploadCV").files.length;
for (var i = 0; i < totalFiles; i++) {
   var file = document.getElementById("fuUploadCV").files[i];
   formData.append("FileUpload", file);
}

// Make sure all other form fields are included
var txtFirstName = $("#txtFirstName").val();
formData.append("txtFirstName", txtFirstName);

$.ajax({
    (... continue with your existing code ...)

Ensure that every form value you wish to send is appended to the FormData object before making the AJAX request.

On the server side, you can access these fields by following the structure in your current code, for example:

[HttpPost]
public void UploadImage()
{
   if (Request.Files.Count > 0)
   {
      dynamic file = Request.Files[0];
      //perform operations with 'file'

      // Access the form fields based on your existing code
      string txtFirstName = Request.Form["txtFirstName"];
      // perform actions using your form data
   }
}

I hope this clarification proves helpful to you.

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 is the best method for incorporating two materials into a mesh that has already been rendered on the canvas?

I've been experimenting with adding both color and an image to a Three.js Mesh after it's already been rendered on the canvas. From what I understand, if I use the same material with both color and a map, they will blend together and there's ...

What causes the parameter to be null when jQuery AJAX sends Content-Type=application/json to an MVC Controller Action method?

Apologies for asking a question that has been addressed multiple times before, but I am unsure if the answers from those discussions are still relevant with the latest versions of ASP.NET Core MVC and jQuery. My MVC controller method accepts a class objec ...

Node(Meteor) experiencing a memory leak due to setTimeout

I have encountered an unusual memory leak associated with the use of setTimeout. Every 15 seconds, I execute the following code using an async function that returns an array of promises (Promise.all). The code is supposed to run again 15 seconds after all ...

After the ajax request is finished, make sure to remove the previous .on()

I have a scenario where I am dynamically loading a partial page using ASP.NET-MVC after making an Ajax request with Ajax.BeginForm. On this loaded partial page, there are some jQuery .on event handlers that cannot be relocated to another place. They rely ...

Send information through a form contained within a jQuery modal pop-up

This question has been brought up before, but none of the solutions provided seem to be effective for my situation. Within a jQuery UI dialog box, I have a form: <!-- Dialog: Register new user--> <div id="dialogForUser" title="Register new user" ...

Determine the amount of clicks and retrieve the URL of the clicked link in Selenium using Python

As a novice in the world of Selenium and Python, I am embarking on the journey of automating banner testing using Python along with Selenium Webdriver. My goal is to keep track of the number of clicks made, ensure that the URLs are redirecting to the corr ...

Color-coded line graph illustrating trends based on values

Can a line chart be created using mschart where the color of different parts of the line varies based on its trend? For example, can the part of the line with ascending values be one color, descending values another color, and equal values yet another co ...

Display issue with the responsive navigation bar

I am currently facing challenges while trying to create a responsive navigation bar. The way it is displayed on the page is not what I intended. Below is an image of how it appears when the window is maximized: https://i.sstatic.net/6NogJ.png And here i ...

How can a method inside an object property of the same class be invoked in JavaScript?

I'm faced with a bit of confusion here. I have a class property called hotspot of type object, declared as follows: Cannon.prototype.hotspot = {stuff: this.blah(...) }; The method blah() is actually a prototype of the same 'class': Canno ...

Passing a class as a parameter in Typescript functions

When working with Angular 2 testing utilities, I usually follow this process: fixture = TestBed.createComponent(EditableValueComponent); The EditableValueComponent is just a standard component class that I use. I am curious about the inner workings: st ...

Unable to send email through Ajax/PHP contact form

It's quite amusing that it worked perfectly for one evening. After reaching out to my host, they assured me that there should be no issues with it not working. I even tried testing it in Firebug, but it appeared to be sending successfully. Additionall ...

Utilizing Angular's ng-repeat with varying directives for each iteration

I am trying to utilize ng-repeat within Angular to iterate through multiple <li> elements with a directive embedded. My goal is to have the first two items in the ng-repeat display differently in terms of styling and content compared to the remaining ...

Setting the z-index for data points in a scatter plot on HighCharts

Utilizing HighCharts to display a large number of points on a plot. Each point has an opacity setting and changes to red when selected. However, some points are difficult to distinguish due to overlapping. I would like the selected point to be easily visi ...

Adjusting the content and style of a div element upon clicking, and restoring the original settings when clicked once more

There is a div with the id #increase-text-weight that displays the text "INCREASE TEXT WEIGHT". Upon clicking on it, the font weight of another div with the id #post-content should be changed to font-weight: 500 and the text inside #increase-text-weight s ...

Using PHP/Symfony2 to display the contents of an object with the print_r

Curious about some strange occurrences, I'm trying to figure out whether they are PHP or Symfony related. Essentially, an ajax request is sent from my form and the form data is then posted to my controller. After persisting the entity in the database ...

Can Selenium in Python be used to locate and extract all concealed elements containing text?

I am currently working on a project where I need to extract translated text from various webpages. I have encountered an issue where the entire page needs to be fully translated before I can begin extracting the text. To achieve this, I have to scroll thr ...

Is there any information available on building a C++ chat server that can communicate with a C# client?

My classmates and I are embarking on the challenge of developing a basic networked game, using a C++ server and a C# client. We understand that this is quite ambitious, but we are looking for any advice or tips to help make this project successful. Unfort ...

Tips for creating a synchronous jQuery "$.post" request

After much research and effort, I have finally come to the last item on my bug fix list. This one involves creating a function that will return true or false to indicate whether the validation was successful. My approach involves using ajax to compare cer ...

Exposed function in JavaScript vulnerable to exploitation

In my application, I have a JavaScript function that redirects users to the login page after a minute: (function redirect_expired() { $j.get('/app/ExpiredSession', function (resp) { if (resp && resp.redirectTo) { ...

Announcing the outcomes I received from JSON notifications

Hey there, I need some assistance. Here's the deal - whenever a user enters something into a text field and then clicks out of it, an ajax request is triggered. $(document).ready(function() { //On Focus lose get content of the first input field $(&ap ...