Transmitting intricate Javascript Array to ASP.NET Controller Function

I am facing an issue with sending a complex JavaScript array to my asp.net mvc6 controller method. I have tried two different methods to pass the data, but neither seem to be working for me.

 public IActionResult TakeComplexArray(IList<ComplexArrayInfoModel> data) 
 {
     return PartialView(data);
 } 

The second method that I tried is:

 public IActionResult TakeComplexArray(ComplexArrayInfoModel[] data) 
 {
     return PartialView(data);
 }

The complex JavaScript array that I am trying to send looks like this:

[Object, Object, Object, Object, Object]

Each object in the array corresponds to my model class type ComplexArrayInfoModel and contains different records of this model class.

Unfortunately, I am unable to successfully send this complex JavaScript array to the controller action using the following JavaScript function:

function SendComplexData(data, row) {
   return $.ajax({
        url: '@Url.Action("TakeComplexArray")',
        /*data.complexArray is showed above schema*/
        data: JSON.stringify({ data: data.complexArray }),
        type: 'POST',
        dataType: 'html',
    });
}

I need help figuring out how to properly send this complex array to the controller action. Additionally, without using the json.stringify method, I am unable to send the data at all.

Answer №1

Have you attempted to utilize Microsoft's MVC.stringify() method for sending the correct data to the MVC controller class? Your JavaScript function should resemble the following:

function SendComplexData(data, row) {
   return $.ajax({
        url: '@Url.Action("TakeComplexArray")',
        /*data.complexArray is displayed in the schema above*/
        data: MVC.stringify({ data: data.complexArray }),
        type: 'POST',
        dataType: 'html',
    });
}

Furthermore, your controller class should be structured as shown below:

public IActionResult TakeComplexArray(IList<ComplexArrayInfoModel> data) 
{
   return PartialView(data);
} 

Feel free to experiment with this Ajax code for sending a complex array to an MVC6 controller action method.

Answer №2

Your use of the $.ajax function is incorrect because you are trying to send form data while actually sending json data. Here are two solutions to correct this issue:

  1. Adjust the dataType to json and set the appropriate contentType:

    $.ajax({
     url: '@Url.Action("TakeComplexArray")',
     contentType: "application/json; charset=utf-8",
     data: JSON.stringify({data: data.complexArray}),
     type: 'POST',
     dataType: 'json'
    });
    
  2. Simply send non-JSON data instead:

    $.ajax({
     url: '@Url.Action("TakeComplexArray")',
     data: {data: data.complexArray},
     type: 'POST',
     dataType: 'html'
    });
    

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

Trigger Modal using PHP/JavaScript

After implementing the code below on my page, I expected guests to be redirected to the main page post login and greeted with a small pop-up modal containing a thank you message. However, despite trying multiple variations of this code, it doesn't see ...

Collaborating on interconnected documents: population dynamics and sophisticated modeling techniques

As someone who is fairly new to these technologies, I'm unsure if I am doing this correctly. I am attempting to display the name of the category in the table instead of the id (which is from the ObjectId schema field) for all the Category documents r ...

Failure to trigger Ajax callback function

I am currently working on a form page that will be submitted using Ajax. The steps I have planned are: 1. Use Ajax to check if the email already exists 2. Verify if the passwords match 3. Switch to another "screen" if they do match 4. Final ...

Variable scope fails to update upon selection change

I'm currently setting up a select dropdown with an ng-options. The dropdown is appearing correctly on the HTML page, but for some reason, when I choose an option, the variable specified by ng-model is not updating in $scope. This is the HTML code: &l ...

Every time Chrome on Android returns a keyCode of 229

Here is a snippet of code that I am having trouble with: ... @HostListener('keydown', ['$event']) onKeyDown(evt: KeyboardEvent) { console.log('KeyCode : ' + evt.keyCode); console.log('Which : ' + evt.which); ...

What steps should I take to host a Node.js application on a subdomain using an apache2 VPS?

Currently, I have a Node.js application that I would like to host on a subdomain using my VPS. The VPS is running apache2 and the Node.js app utilizes Express. Despite trying both Phusion and following this tutorial, I have been unsuccessful in getting i ...

Implementing jQuery functionality on elements that are generated dynamically

I'm facing a challenge when working with dynamic elements in jQuery and I really could use some help. Let me provide an example from my current project: main.js $(function () { renderPlaceList(places); setupVoting(); } The two functions are ...

Modify JSON date format to a shorter version using the first 2 letters of the month and the year

Looking to convert date values in a JSON array from "December 2016" format to "D16". Hoping to accomplish this using Regex, any assistance would be greatly appreciated. [["November 2016","December 2016","January 2017","February 2017","March 2017"],["tot ...

Converting an onclick event to onsubmit: Tips for doing it right

Recently, I had to add validation to a file upload form for our Google Drive. After some research, I discovered that using onsubmit instead of onclick was the way to go. However, when I made the switch from onclick to onsubmit, the validation worked but t ...

Using a carousel component in Bootstrap

Just starting out with this, trying to customize Bootstrap to change slides automatically. I followed the documentation at https://getbootstrap.com/docs/4.3/components/carousel/ but for some reason, the slides aren't changing on an interval, even thou ...

Steps for updating placeholder text when a user makes a selection

My asp form group currently has two option values - one for country and the other for state/province. Is there a way to switch the text depending on the selection? For instance, when Canada is selected, the placeholder text will be Province, but when U.S ...

Encountering the "potential null object" TypeScript issue when utilizing template ref data in Vue

Currently, I am trying to make modifications to the CSS rules of an <h1> element with a reference ref="header". However, I have encountered a TypeScript error that is preventing me from doing so. const header = ref<HTMLElement | null> ...

Tips for iterating within a Vue.js template without disrupting the HTML structure

Currently, I am attempting to implement a loop within a table. However, I have encountered an issue with the following code: <tr v-for="( block , index ) in listRenderBlock" :key="index"> <div v-for="( section , i ) in ...

Issue detected: data exceeds limits (length=3, offset=32, code=BUFFER_OVERRUN, version=abi/5.0.7) within next-js and ethereum

While working on my Ethereum and Next.js project, I encountered an error during the initialization of the project: Error: data out-of-bounds (length=3, offset=32, code=BUFFER_OVERRUN, version=abi/5.0.7) at Logger.makeError (/home/Documents/projects/eth ...

Changing the value of a JSON object

My goal is to update a value in a JSON file by removing the last character from a URL. I wrote the following code, but unfortunately, it doesn't seem to be making any changes. I'm a bit lost on what went wrong... def modify_json(file): with ...

Maintain the state of the toggle div after page refresh or modification

In this scenario, I am looking to ensure that my div remains open even if the page is changed or refreshed. Below is the HTML and JavaScript code provided: You can view the working code here: http://jsfiddle.net/wasimkazi/fauNg/1/ $(".widget2").hide( ...

Extracting specific data from a JSON subnode within an HTML document

I have been attempting to retrieve product data (name, price, url), along with information on available sizes and colors, from a website that is formatted in JSON (https://www.bergzeit.de/marken/salewa/). However, I am struggling to locate the 'elemen ...

Creating a vertical bar chart in D3 with a JSON data source embedded within the code

Struggling to generate a stacked bar graph in D3.js. The axes are displaying correctly, but the data on the graph is not showing up. Any suggestions on what could be causing this issue? JS: var svg = d3.select("#recovery__table"), margin = {top: 20, ...

Using JavaScript to Filter Through Numerous Values Based on Different Attributes

My goal is to efficiently filter multiple attributes with multiple values 'arr' represents a list of all products, and 'f_...' indicates the attribute such as color or type. 'namet' denotes the selected attribute by the user ...

Is it possible to extract content from a remote website by utilizing javascript and iframe?

Are there any resources available for working with iframes in Ruby on Rails? **UPDATE:** I have a link that directs to an external website. I am looking to extract the content from that site and save it within my application. Is this achievable without re ...