Using ASP.NET MVC to map FormData with an array to a model class

I am currently facing an issue with mapping a list of objects in a FormData to my ASP.NET MVC Model class at the controller. I have successfully sent the FormData over to the server-side, but I am unable to bind any value. Can someone provide guidance on how to correctly map the objects? Below is the code snippet I am currently working with:

Update I am still struggling with this problem and any help would be greatly appreciated! Update2 Just to clarify, I am utilizing Vue.js as my client-side framework

Client-side

  const formData = new FormData();

  formData.append("Product[0].ProductName", "T-Shirt");
  formData.append("Product[0].Options.Quantity", "1");
  formData.append("Product[1].ProductName", "Shoe");
  formData.append("Product[1].Options.Quantity", "2");

Server-side (Controller)

    [HttpPost("verifyCart")]
    public async Task<IActionResult> verifyCart([FromForm] Product[] products)
    {
    }

Server-side (Model)

public class Product
    {
        public string ProductName { get; set; }
        public List<Option> Options { get; set; }        
    }


public class Options
    {
        public int Quantity { get; set; } 
    }

Answer №1

By making a simple change in the form data, I was able to get it to work:

formData.append("Product[0].ProductName", "T-Shirt");
formData.append("Product[0].Options.Quantity", "1");
formData.append("Product[1].ProductName", "Shoe");
formData.append("Product[1].Options.Quantity", "2");

All I had to do was change "Product" to its plural form:

formData.append("Products[0].ProductName", "T-Shirt");
formData.append("Products[0].Options.Quantity", "1");
formData.append("Products[1].ProductName", "Shoe");
formData.append("Products[1].Options.Quantity", "2");

This change was necessary because the parameter used in the post action is "products":

[HttpPost]
public IActionResult VerifyCart([FromForm] Product[] products)
{
}

To test this on the client side, I made sure to update my code accordingly:

const formData = new FormData();

    formData.append("Products[0].ProductName", "T-Shirt");
    formData.append("Products[0].Options.Quantity", "1");
    formData.append("Products[1].ProductName", "Shoe");
    formData.append("Products[1].Options.Quantity", "2");

    $.ajax({
            type: "POST",
            url: '/Home/VerifyCart',
            data: formData,
            processData: false,
            contentType: false,
            success: function (data) {
            }
     });

Update

To address the Quantity issue, I decided to modify the client-side code as follows:

const formData = new FormData();

    formData.append("Products[0].ProductName", "T-Shirt");
    formData.append("Products[0].Options[0].Quantity", "1");
    formData.append("Products[1].ProductName", "Shoe");
    formData.append("Products[1].Options[0].Quantity", "2");

    $.ajax({
            type: "POST",
            url: '/Home/VerifyCart',
            data: formData,
            processData: false,
            contentType: false,
            success: function (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

Iterating through a legitimate JSON object and storing each data value in a separate variable

I am currently utilizing jQuery. To further elaborate on my previous question, I have executed an Ajax request using the jQuery $.ajax function with a PHP script. The PHP script returned a JSON object which was validated when tested with link text. I am p ...

The Challenge() function consistently leads users to the Login Page

When attempting to authorize my Action method, everything seems to be functioning correctly except for the Challenge() method. It consistently redirects to the Login Page, even though I am already logged in. Upon trying to return the Forbid() method, it ...

Module not found in Node.js Express JS

I've read several topics on this issue here at stackoverflow, but I am still unable to get my node application running. When I try to run the command: node app.js local I receive the following error: Error: Cannot find module './config' ...

We were unable to find an existing Kibana index, therefore we are unable to establish a connection

When setting up vue-storefront-api and vue-storefront on my Windows machine, I encountered an error in windows Power Shell or Command Prompt while running docker-compose up. The error message stated that no existing Kibana index was found, along with the i ...

Exploring the integration of datatables.net-vue3 with Vue.js 3 in Visual Studio: A step-by-step guide

I am trying to integrate datatables.net-vue3 with Vue.js 3 in Visual Studio. I have installed it using npm like so. However, I am facing issues with the imports in Visual Studio. I have tried importing them this way but it doesn't seem to work for me ...

Transitioning images in JQuery by using a rollover effect

Is there a way to use Jquery for a hover effect that transitions images with a slide up animation? I've looked everywhere online, but I can't seem to find a code that works. All the examples I've found use fadeIn or fadeOut. Thank you for yo ...

Working with Vue's v-for directive to bind computed properties

I am inputting a set of tasks into my v-form tasks: [ { title: 'title1', description: 'task 1 description', isComplete: functionA() }, { title: 'title2', ...

Ways to dynamically emphasize text within ngFor loop

Within my ngFor loop, I have a set of rows. <div *ngFor="let block of data;"> <div class="class-row"> <div class="left">A Label:</div> <div class="right">{{block.key1}}</div> </div> <div class="clas ...

Toggle visibility on the child DOM element of each item in the v-for loop

Here's an example of a template: <template> <table class="table table-hover"> <tbody> <tr> <th style="width:260px">Info</th> <th>Deta ...

What is the process for converting a multidimensional array from PHP into JavaScript?

Recently, I've been experimenting with dygraph. To populate my graph, I fetch data via an ajax call and then need to convert the returned JSON array into a JavaScript array. My dygraph options are set up like this: series = { sample1: { ...

Using Node JS, how to pass a variable length array to a function?

Is there a way to dynamically call an addon function with varying argument lengths? I capture user input in a variable like this: Uinput = [5,3,2]; Now, I want to pass these numbers as arguments to my addon function like this: addon.myaddon(5,3,2); I n ...

What is preferable: defining JSON schema properties or utilizing oneOf conditions within an array of objects

I am looking to represent a variety of objects in a schema through an array called contents. This array can include any number of elements, but they must fall into one of two categories: one type represents text while the other type represents images. Up ...

Why does my POST request result in [object Object] being returned?

I am just starting to learn AngularJS and I am unsure if my POST request is functioning correctly. After making the request, I am receiving an [object Object] response. What does this error indicate? Could it be related to an issue with the form? //Acti ...

Default Selection Issue with Radio Buttons in AngularJS

I am currently encountering an issue with the code snippet included in my directive template '<li ng-repeat="f in foos">' + '<input type="radio" ng-change="foo(f.key)" ng-model="selectedFoo" name="foos" id="{{f.key}}" value="{{f.ke ...

Identify when objects in kineticJS are dropped

Key Concept Designing a match-the-following activity where red dots can be dragged to blue dots on the left. The draggable red dots must accurately match with the blue target dots. Objective Assigning values to each dot, and ensuring that once a red do ...

What is the reason for the absence of Duplex Stream in the Web Streams API?

I have experience working with the traditional nodejs stream, which makes the need for Duplex streams quite evident. These are streams that can both read and write data, like net.Socket. As mentioned here Examples of Duplex streams include: TCP sockets ...

What could be causing the beforeRouteUpdate function to not successfully update the route

I have implemented the products page using vueJS and an API. The page displays categories on the left side and products on the right side. The goal is to show products when a category is clicked, but the component is not loading as expected. I need help ...

Utilize AngularJs and JavaScript to upload information to a JSON file

Exploring the realm of Angular JS, I am on a quest to create a CRUD form using AngularJs and Json with pure javascript without involving any other server side language. The script seems to be functioning well but is facing an obstacle when it comes to writ ...

Managing multiple updates or inserts in a MSSQL database using Sequelize

I have been tirelessly searching the online realms for a resolution over the past day but to no avail. The task at hand is performing a bulk upsert (update or insert) of a single model into a mssql database. Unfortunately, using bulkCreate with updateOnD ...

Our connection to [ws] was unexpectedly interrupted as the page was in the process of loading, all while utilizing Vue CLI within Firefox and a proxy

Here are the steps you should follow to reproduce the issue: To begin, make sure to install Vue CLI and create a new Vue CLI project by running vue create test-project. Be sure to use Vue 3 along with Yarn. You will need to update the vue.config.js file i ...