Techniques for sending a list of objects to a method using AJAX in MVC

Hey there, I am facing an issue with passing a list in an ajax call to my controller as I am getting null data.

Below is the code snippet:

Class:

public class CurrentProcessNameAndBucketName
{
    public string ProcessName { get; set; }
    public string BucketName { get; set; }
    public int Id { get; set; }
    public int AccountId { get; set; }
    public int FromProcessId { get; set; }
    public int FromBucketId { get; set; }
    public int ToProcessId { get; set; }
    public int ToBucketId { get; set; }
    public string FromRefField { get; set; }
    public string ToRefField { get; set; }
    public int UserId { get; set; }
}

Controller:

        [HttpPost]
        [Authorize]
        [Route("api/Master/Workflow/InsertRefFieldClone")]
        public bool InsertRefFieldClone(List<BusinessEntities.Master.CurrentProcessNameAndBucketName> item)
        {
            try
            {
                BusinessLayer.IMaster.IWorkflow a = (BusinessLayer.IMaster.IWorkflow)DALFinder.GetInstance(typeof(BusinessLayer.IMaster.IWorkflow));
                for (var i = 0; i < item.Count(); i++)
                {
                    a.InsertRefFieldClone(item[i]);
                }
                return true;
            }
            catch (Exception ex)
            {
                Utils.Logger.Instance.LogException(ex);
                return false;
            }
        }

My front end:

const saveDetails = [];
const dataLength = tbody_Copy.children().length;
for (let i = 0; i < dataLength; i++) {
    const saveDetail = [];
    saveDetail.Id = 0;
    saveDetail.AccountId = Utils.getCurrentUser().AccountId;
    saveDetail.FromProcessId = ctrlProcess.val();
    saveDetail.FromBucketId = ctrlBucket.val();
    saveDetail.ToProcessId = processId;
    saveDetail.ToBucketId = bucketId;
    saveDetail.FromRefField = $('#' + tbody_Copy.children().eq(i).find('SELECT').attr('id')).val();
    saveDetail.ToRefField = tbody_Copy.children().eq(0).children().eq(1).text();
    saveDetail.UserId = Utils.getUserId();
    saveDetails.push(saveDetail);
}
const data = saveDetails;
var access_token = Utils.getToken();
$.ajax({
    url: Utils.getWebApiUrl() + "/api/Master/Workflow/InsertRefFieldClone",
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify(data),
    dataType: 'json',
    type: 'POST',
    beforeSend: function (xhr) {
        xhr.setRequestHeader('Authorization', 'bearer ' + access_token);
    },
    success: function (response) {
        debugger
    },
    failure: function (response) {
        Utils.showError(JSON.stringify('Records cannot be saved please try again later.'));
    },
    error: function (response) {
        Utils.showAlert(response.responseText);
    }
});

I'm having trouble identifying the issue in my code despite reviewing various resources. Any assistance would be greatly appreciated.

Answer №1

It is recommended to initialize your detail using an object instead of an array:

const saveDetail = []; // incorrect

const saveDetail = {}; // correct

For more information, you can visit this page

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

Retrieving intricate JSON data from a specific web address

I need assistance in extracting and printing the date value from the JSON content available at the specified URL. Specifically, I am looking to retrieve the date value of "data.content.containers.container.locationDateTime" only if the "data.content.conta ...

Receiving a Promise<fullfield> as a result

I have a situation where I am adding several promises to an array: const apiCallsToMake = []; apiCallsToMake.push(this.getDataFromUnsplash(copyInputParams)); apiCallsToMake.push(this.getDataFromPexels(copyInputParams)); apiCallsToMake.pu ...

When the limit is set to 1, the processing time is 1ms. If the limit is greater than 1, the processing time jumps to

Here is the MongoDB Native Driver query being used: mo.post.find({_us:_us, utc:{$lte:utc}},{ fields:{geo:0, bin:0, flg:0, mod:0, edt:0}, hint:{_us:1, utc:-1}, sort:{utc:-1}, limit:X, explain:true }).toArray(function(err, result){ ...

Exploring the srcObject feature in React NativeDiscovering the ins and

I am currently working with react native web technology. React-Native-Web: https://github.com/necolas/react-native-web One of the requirements is to incorporate a Video tag. I have developed a video component using CreateElement. Here is the video compo ...

What is the best way to use HTML5 canvas and JavaScript to crop an image offline?

While there are many online tools available to crop an image using JavaScript and PHP, the challenge arises when we want our app to function strictly offline without relying on server-side PHP scripting. In order to achieve this, we must turn to HTML5 ca ...

The webmethod does not respond to the AJAX function

I am facing an issue with two separate ajax functions on my webpage. One function works perfectly when a link inside a grid is clicked, while the other one produces an error every time a button is clicked. I need help in identifying where I am making a mi ...

At what point are functions executed? What methods can I use to manage their execution?

Looking to make a simple call to an API using jQuery's $.get() function as a JS beginner. The issue I'm facing is that the function seems to be called randomly rather than where I expect it in my code. I am open to either doing everything inside ...

How do I go about configuring the uploaded image?

Here is a sample of my HTML code: <div class="images"> <figure> <button id="upload-add-product" class="icon-plus"></button> <input id="upload-file" type="file" style="display: none;" multiple/> </fi ...

Oops! Looks like we couldn't locate the request token in the session when attempting to access the Twitter API

Every time I attempt to connect to the Twitter API using Passport OAuth, an issue arises that redirects me to an error page displaying this message: Error: Failed to locate request token in session at SessionStore.get (/Users/youcefchergui/Work/ESP/socialb ...

Steps for installing an npm package from a downloaded folder

In the past, I had a method of installing an npm project from Github that involved using git clone followed by npm install. git clone http...my_project npm install my_project Instead of manually copying the contents of my_project to my local node_modules ...

Exploring a JavaScript file with the power of JavaScript and HTML

I have a .js file that contains the following data (excerpt for brevity) var albums= "tracks":[ {"title":"Dunnock","mp3":"Birdsong-Dunnock.mp3", "lyrics":"The Dunnock or hedge sparrow has a fast warbling song often delivered from t ...

Storing the selected radio button value in AsyncStorage using React Native: A step-by-step guide

Can anyone help me with storing the users selected radio button value in AsyncStorage? I have radio button values being retrieved from another file and assigned to labels. Here is an example of how my radio buttons are structured: import RadioButtonRN fr ...

Incorporating the chosen value from a dropdown box as a variable in PHP

Seeking assistance with using the value selected in a drop-down box as a PHP variable in my functions.php file. I attempted to utilize jquery-ajax for this purpose. $(document).ready(function(){ $("#pa_color").change(function(){ var result= $(this).val( ...

"Enhance your website with the dynamic duo of Dropzone

Currently, I am utilizing dropzone.js and loading it through ajax. I have assigned my menu ID as "#menu". The uploaded file should display in "#div1". Unfortunately, the callback function is not functioning properly. In an attempt to troubleshoot, I repl ...

Exploring the Fusion of Material UI Searchbox and Autocomplete in React

Looking for help with my AppBar component from Material UI. I want the Searchbox field to function similarly to what is seen on https://material-ui.com/. It should appear as a Searchbox but display selectable options like Autocomplete after entering input. ...

When running nodemon in an npm project without any arguments, it fails to execute the value specified in the "main" field of the package.json

My current npm project has the following folder structure: project ├── node_modules │ └── (node_modles folders) ├── server.js ├── index.js ├── index.html ├── package.json └── package-lock.json The JavaScr ...

Logging out in a Model-View-Controller (MVC) architecture

After creating a website using MVC4 razor, I have encountered an issue with redirecting views using both "@Ajax.ActionLink" and "@Html.ActionLink". The problem arises when the user is on a view that uses @Ajax.ActionLink and their session expires - in this ...

Utilize ramda.js to pair an identifier key with values from a nested array of objects

I am currently working on a task that involves manipulating an array of nested objects and arrays to calculate a total score for each identifier and store it in a new object. The JSON data I have is structured as follows: { "AllData" : [ { "c ...

Seeking a light-weight, text-rich editor specifically designed for use on our enterprise website. This editor should be even lighter than TinyMCE

I am in search of a lightweight text editor for an enterprise website, lighter than tinymce with basic buttons for the comment form. It is imperative that the editor also functions properly in IE6. So far, I have tried cleditor 15KB, but it has an issue in ...

Positioning customized data on the doughnut chart within chart.js

Is there a way to customize the position of the data displayed in a doughnut chart? Currently, the default setting is that the first item in the data array is placed at 0 degrees. However, I need to place it at a custom position because I am working on a ...