The C# method is receiving a null array through Ajax

When I retrieve an array in a loop and pass it through an ajax call to my C# method, I'm encountering a problem where only null values are being received in my parameter. The count of the array is coming through, but the actual data seems to be lost. Before passing it through the ajax call, the array has a count of 3 with all the necessary information populated. However, when debugging in Visual Studio, the parameter for the list ends up being null while still maintaining a count of 3?

let test = $('.divtest').map(function (index, element) {

    return {
        key1: $(element).closest('.testdiv')[0].id,
        key2: $(element).attr('id'),
        key3: $(element).attr('style')
    }
}).get();

Ajax Call

$.ajax({
    cache: false,
    type: "POST",
    data: { test: test},
    dataType: "json",
    url: "/controller/testhere",
    success: function (result) {
      alert('done');
    }
});

C# Method

 public JsonResult testhere(List<string> test)
    {
       //stuff
        return null;
    }

Answer №1

your function requires a list of strings, but the AJAX data does not match that format. You can try using the following data structure:

let test = [ "key1", "key2", "key3"];
.....
.ajax({
    cache: false,
    type: "POST",
    data: { test: test},
    dataType: "json",
    url: "/controller/testhere",
    success: function (result) {
      alert('done');
    }
});

Alternatively, you may need to modify the function.

Create a view model

public class TestViewModel
{
public string Key1 {get; set;}
public string Key2 {get; set;}
public string Key3 {get; set;}
}

Function

public JsonResult testhere(TestViewModel test)

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

Utilize the latest REDUX state within a React component's function

I'm currently facing an issue in my React application where I am struggling to access the updated state from within a function. Here is a simplified version of my problem: I have a custom React Component to which I pass a variable representing the st ...

What is the quickest method for retrieving information from a remote filesystem using WMI?

I'm currently in the process of recursively retrieving all files—approximately 5 or 6 files, more or less—within the directory C:\YC. I'm limited to making just one WMI call to a remote computer. Although I've successfully made thi ...

Is there a way to customize Angular's number filter?

I'm trying to achieve a consistent number format with Angular's number filter, regardless of the localization selected. After inspecting the Angular source code on GitHub, I found the implementation of the filter to be like this: function number ...

Postback asynchronously after clicking on a node in the master page's treeview

My application is being developed using ASP.NET MVC. I have implemented a treeview in the masterpage, with each treenode containing href links. When a treenode is clicked, the corresponding page loads in the content view. I want this process to occur asy ...

Check if there are any child nodes before executing the RemoveChild JavaScript function to avoid any errors

function delete(){ let k = document.getElementsByClassName('row'); for(let i=0; i<k.length; i++) { if(k[i].hasChildNodes()){ k[i].removeChild(k[i].childNodes[2]); } } } <div id="table"> <div class="row"& ...

Commitment without anticipation of a resolution or rejection

While testing one of my AngularJs Services, I decided to write some Unit tests. Below is a sample code snippet that I have come up with: it('', function(done) { aDocument.retrieveServiceFile(extractedFileFeature) .then(function() { ...

Transfer data from a file to a PHP file using the XMLHttpRequest object in JavaScript and receive

I'm attempting to use AJAX to send an image file to a PHP file. The issue is that even though the script sends the object, my parser isn't able to retrieve the $_FILES["avatar"]["name"] and tmp_name values. Is there a method to transfer the file ...

The PHP code fails to output the JSON-formatted array

I'm facing an issue with a php script that is supposed to display multiple datasets in a json encoded string, but instead, the page appears blank. <?php $con = mysqli_connect("SERVER", "USER", "PASSWORD", "DATABASE"); if(!$sql = "SELECT news.titl ...

What is the method to incorporate the current time into a date object and obtain its ISO string representation?

I'm using a ngbDatePicker feature to select a date, which then returns an object structured like this: {year:2020, month:12, day:03} My goal is to convert this date into an ISOString format with the current time. For example, if the current time is 1 ...

Retrieve all entries and merge a field with aggregated information in Mongoose (MongoDB)

I am faced with the challenge of working with two Mongo collections, Users and Activities. The Activities collection consists of fields such as createdAt (type Date), hoursWorked (type Number), and a reference to the user through the user field. On the oth ...

Component updates are not working in VueJS

My Vue 1 component requires an object as a prop that needs to be filled by the user. This object has a specific structure with properties and nested inputs. The component is essentially a modal with a table containing necessary inputs. I want to perform v ...

Is there a way to retrieve a key-value map from JsonNode?

There is a JSON file that I have with the following structure: { "data": { "k1": "v1", "k2": "v2", ... } } Is there a way to extract the keys and values from this JSON file as a Map<String, String> using pathpath? This is how I am ...

Performing an XMLHttpRequest in the same JSP file using Javascript

I am working on a JSP file that contains three dropdown boxes labeled "countries", "regions", and "cities". My goal is to populate the regions based on the selected country, and the cities based on the selected region. I have managed to achieve this using ...

Beginning a counter: a step-by-step guide

I am currently utilizing Angular to create a functional counter like so: <button ng-click="order.startOperation(operation)"> <p ng-if="counter.start"></p> </button> When the button is clicked, it triggers a function that initia ...

What is the best way to transfer data from an Ajax function to a controller action?

I have a button in my view that triggers a jQuery Ajax function, with parameters fetched from my model <input type="button" value="Run Check" onclick="runCheck('@actionItem.StepID', '@Model.Client.DatabaseConnectionString', '@M ...

Encountering issues with AngularJS number filter when integrating it with UI grid

When using the angularjs number filter in angular-ui-grid, I am facing an issue. The filter works perfectly fine within the grid, but when I export the grid to csv and open it in Excel, the formatting is not maintained. I have included the filter in the e ...

Unsuccessful response from an AJAX callback function

Issue: I am able to successfully pass a value to the ajax method and execute a Select SQL query (results visible in Network tab), but I never receive any results back (I expect an alert saying "Success"). What could be causing this issue? HTML: function ...

What is the best way to display these images correctly within a slider?

My goal is to display 4 images/company logos per slide, but they all end up clustered on one slide. Despite my efforts to adjust the CSS, nothing seems to work. This is what my code currently renders: Here are the react component codes I am using: To se ...

What method should be used to transfer a pointer as a parameter to a function?

If I create a function that prints out elements of a multi-dimensional array, how can I ensure it works correctly? int print(int *a) { for (int i=0;i<4;i++) { for(int j=0;j<4;j++) { cout<< *((a+i*4)+j);} } } return 0;} When attempting to c ...

Utilizing JSX interpolation for translation in React JS with i18next

I am trying to utilize a JSX object within the interpolation object of the i18next translate method. Here is an example code snippet along with its result: import React from "react"; import {useTranslation} from "react-i18next&qu ...