Sending a JSON array in an AJAX request results in receiving null values in an MVC application

I've been trying to send an array of JSON objects to my controller action, but it keeps showing up as null.

Here's the JavaScript code I'm using:

function UpdateSelected() {
    var items = {};

    //Loop through grid / sub grids and create json array
    $('.k-detail-row .k-grid').each(function () {
        var grid = $(this).data("kendoGrid");
        var selectedElements = grid.select();
        for (var j = 0; j < selectedElements.length; j++) {
            var item = grid.dataItem(selectedElements[j]);
            var json = item.toJSON();
            items = [].concat(items, json);
        }
    })

    //shift the first empty space out
    items.shift();

    //items is ready to send
    alert(JSON.stringify(items));
    $.ajax({
        cache: false,
        url: '/Update/GetSchematicsForSelectedVariants',
        type: 'GET',
        data: JSON.stringify(items),
        success: function (data) {
            alert("success");
        }
    });
}

This is what the JSON array looks like:

https://i.stack.imgur.com/oRW3p.png

And here's my Controller Action:

public JsonResult GetSchematicsForSelectedVariants(List<VariantViewModel> vm)//vm coming in null
{
    return Json(_dataAccessService.GetSchematicsForMacroVariants(vm),JsonRequestBehavior.AllowGet);
}

VariantViewModel Class:

public class VariantViewModel
{
    public string Id { get; set; }
    public string Variant { get; set; }
}

I can't figure out why my list is being passed in as null. I'm not very experienced in passing JSON objects to the controller, but I think I have the basics down. Any advice on where I might be going wrong would be greatly appreciated.

If anyone could help point me in the right direction, that would be fantastic!

Answer №1

After some investigation, I discovered the root of the issue. It turns out that my data needed to be formatted a specific way in the AJAX request. Surprisingly, this small detail had escaped my notice initially.

$.ajax({
        cache: false,
        url: '/Update/GetSchematicsForSelectedVariants',
        type: 'POST',
        data: {'ListOfVariants' : items},
        success: function (data) {
            alert("success");
        }
    });

I appreciate all the comments from everyone as they played a crucial role in guiding me towards the solution.

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

Modifying the names of certain keys within a JSONArray

After receiving a JSONArray response from an HTTP request, I noticed that some of the keys in the JSON response have names like Total_x200_Price or Creation_x200_Date, where spaces are represented by "x200" instead of actual spaces. This is causing issues ...

Utilize the power of REACT JS to transform a specific segment within a paragraph into a hyperlink. Take advantage of the click event on that hyperlink to execute an API request prior to

In React JSX, I'm encountering an issue trying to dynamically convert a section of text into an anchor tag. Additionally, upon clicking the anchor tag, I need to make an API call before redirecting it to the requested page. Despite my attempts, I have ...

Modify the AJAX data in Datatables without directly modifying the elements

I am currently working with a Datatable that is being populated through AJAX, and everything is going smoothly. However, I am looking for a way to include some shortcuts to send requests to the server. The issue lies in how I can modify the data being sent ...

Execute the query with a join clause

In my database, I have two tables: [Departments] with ID, Department_Name, and [Employees] with Emp_ID, Emp_Name, and Dep_ID as a foreign key to Departments.ID My goal is to first select all Department Names and display them in a dropdown list from the De ...

AngularJS Chrome Extension has been flagged as potentially harmful, despite the implementation of compileProvider.aHrefSanitizationWhitelist. This has resulted

I have previously shared this issue, however, the suggested solutions did not resolve it. Therefore, I am reposting with a more widely recognized solution: I am currently working on developing a chrome extension using AngularJS. In my base directive, I am ...

Emphasize table cells dynamically

Query How can I dynamically highlight a selected td? Codepen Example View Pen here Code Snippet The map consists of a randomly generated 2D array, like this: map = [[1,1,1,1,0], [1,0,0,0,0], [1,0,1,1,1], [1,0,0,0,1], [1,1, ...

Methods for organizing consecutive elements within an array in Javascript/Typescript

Let's explore this collection of objects: [ { key1: "AAA", key2: "BBB" }, { key1: "BBB", key2: "CCC" }, { key1: "CCC", key2: "DD ...

Ways to stop a JavaScript function from running during page loading

After clicking the submit button on my form, I want to send a confirmation post using the sendPostAjax() function before submitting the form to the payment provider. However, I'm facing an issue where the sendPostAjax() function is getting executed as ...

Initiate Ant Design select reset

I am facing an issue with 2 <Select> elements. The values in the second one depend on the selection made in the first one. However, when I change the selected item in the first select, the available options in the second one update. But if a selectio ...

Can the mDNS string received through webRTC be decoded to retrieve a user's IP address?

After doing some thorough research, I came across this insightful response from a different Stack Overflow question. The problem at hand involves retrieving an mDNS string, which looks like this: abcd1234-1e1e-1e1e-1e1e-abcd1a2bc3de.local I have a genuin ...

What is the best way to add a value to the value attribute of a div using JavaScript?

Is there a way to insert a value into the value attribute of a div using Internet Explorer 9? I have attempted various JavaScript functions, but so far I can only modify the content inside the div and not the value attribute itself. <div id="mydiv" val ...

How can I troubleshoot the issue of not being able to display elements in my list in

I am struggling with an issue regarding my patient list. I am trying to create a JTree from my JSON list by converting it into a regular list. However, I am unable to display the name of each patient. Please review my code below and provide any suggestions ...

jspdf generates blank PDF files

I am trying to use JsPDF to generate a PDF from content within a Section tag. I have followed various guides but none of them seem to be working for me. Since there is no demo code available, I am turning to this platform in hopes of finding a solution. A ...

Navigating a single page application with the convenience of the back button using AJAX

I have developed a website that is designed to function without keeping any browser history, aside from the main page. This was primarily done for security reasons to ensure that the server and browser state always remain in sync. Is there a method by whi ...

Submitting form data via Ajax without refreshing the page

I am trying to submit my form using Ajax without refreshing the page. However, it seems that the $_POST values are not being picked up. I don't receive any errors, but I suspect that my form is not submitting correctly. HTML Form <form action="" ...

TravisCI - Deploying Asp.net to a Linux Server

Although I can successfully build my asp.net 4 (MVC) Application using TravisCI.org, I am facing difficulties in transferring the output from Travis to my Linux server. I am thinking of resolving this issue by creating a *.sh file, but I am unsure about h ...

Is there a way to configure MaterialUI XGrid filters to target and filter by the renderCell parameters instead of the backend data source?

While utilizing MaterialUI XGrid to showcase rows of information, I am facing an issue with filtering. Currently, filtering can only be done based on the backend row values rather than what is displayed in the cell. For instance, consider a column named U ...

Storing JSON data in a Postgres database using Elixir and Phoenix

I have searched extensively for solutions to this problem. Utilizing the phx.gen generator, I created some CRUD functionalities. My goal is to establish repositories in my database and store GitHub activity within them. Here is my migration: def change ...

Stopping the parent onclick event from propagating to a child element within a bootstrap modal

I am currently working with angularjs and bootstrap, incorporating nested onclick events using Angular's ng-click in various HTML elements. One is located in a table header to display different sort icons and execute the sorting logic when the header ...

Interactive hexagon shape with dynamic image content on click using a combination of CSS, HTML,

As a beginner in CSS, HTML, and JavaScript, I came across a code snippet to create a pattern of hexagons with images (refer to the first code below). My goal is to change the image displayed on a clicked hexagon to another picture (see second code). First ...