Comparison: Storing a Group of Objects versus Saving Individual Objects in C#

I've successfully implemented the following code:

Class (objects declared)

public class saveRow
{
    public int proId { get; set; }
    public string proName{get;set;}
}

Controller:

[HttpPost]
public virtual JsonResult SaveRow(saveRow input)
{ /* CODE HERE */}

JavaScript Object (Sent)

var test = {"proId" : 1, "proName" : "Test"}

JavaScript Ajax Call

 $.ajax({
       type: "POST",
       url: "URL",
       dataType: "json",
       data: test,
       traditional: true,
       success: function (data, status, request) {
           if (data.Error != undefined) {
               alert("System Error: " + data.Error);
               $(row).find('*').attr('disabled', false);
               return;
           }

       },
       error: function (request, status, error) {
           console.log("ERROR");
       }
   });

The issue arises when attempting to send a list of rows instead of one at a time. To test this, I duplicated the object like so:

To test i took the same object and done

var test2 = []; test2.push(test); test2.push(test);

And now the object is as follows:

[{"proId" : 1, "proName" : "Test"},{"proId" : 1, "proName" : "Test"}]

My controller has been updated to:

[HttpPost]
public virtual JsonResult SaveRow(List<saveRow> input)
{ /* CODE HERE */}

Despite also trying with IEnumerable, the "input" parameter in the controller remains null when sending a list of objects as JSON.

What could be causing this?

Solution Found:

public virtual JsonResult SaveRow(saveRow[] input)

Don't forget to include content type! And use JSON.stringify!

Answer №1

Here is a suggested approach:

  • Create a wrapper with the same name as your argument, "input"
  • Specify the content-type
  • Instead of using traditional methods, utilize JSON.stringify to convert your data into a string.

JavaScript:

var data = { "input": test2 };

$.ajax({
       type: "POST",
       url: "URL",
       dataType: "json",
       contentType:"application/json; charset=utf-8", //<-- Specify Content Type
       data: JSON.stringify(data), // Set Data
       success: function (data, status, request) {
           if (data.Error != undefined) {
               alert("System Error: " + data.Error);
               $(row).find('*').attr('disabled', false);
               return;
           }

       },
       error: function (request, status, error) {
           console.log("ERROR");
       }
   });

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

Sending a JSON payload via a POST request to a Minimal API service

I have set up a minimal API service that uses MapPost: app.MapPost("/sendmessage", (RabbitMessage rm) => server.SendMessage(rm.exchange, rm.routingkey, rm.message)); app.Run(); record RabbitMessage(string exchange, string routingkey, string ...

Add the item to a fresh array using the Ajax function

Here is an array that I have: var arrayOfResults = []; // Results after like statement After making a database call, I receive a JSON result like this: [{ "id": "{fcb42c9c-3617-4048-b2a0-2600775a4c34}", "pid": "{34214CCB-90C3-4D ...

Updating HTML content using jQuery by iterating through an array

When I write the following HTML code: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <h1 id="message"> </h1> and include the corresponding JavaScript code: messages = ["Here", "are", ...

Sending an Ajax request using jQuery to a Jenkins job

var milestone_name = uiscripts.context.milestone.name; //AJAX block start $.ajax({ url: "https://ctu-automation-server:8080/job/Check/build", type: "GET" }); //AJAX block end When the above ajax call is made from a remote serv ...

Ajax redirection with Symfony

The login page utilizes ajax, with the controller responding in the web browser view as {"response":true,"data":{"from":"apachecms_api_login_submit","to":"/dashboard"}} without redirecting. When successful, the function triggers an ajax call. functio ...

Incorporating a new chapter into the annals using a Chrome extension

Is it feasible for a Google Chrome extension to create a covert tab that secretly navigates to a specified URL? For instance, if I choose to visit www.google.com, the tab's URL would mirror this without being visible to the user. The only way to confi ...

Step-By-Step Guide on Creating a Data Post Using HttpUrlConnection

Here is an AJAX code snippet I have: $.ajax({ url: 'http://www.whoisxmlapi.com/whoisserver/WhoisService', dataType: 'jsonp', type:'POST', data: { domainName: 'domaindomanin.com', outp ...

What is the best way to assess each item in an array and apply the useState() hook based on a specific condition

I am currently working on a simulation for a blackjack hand and have run into an issue with my code. The game follows these steps: users receive two random cards and a total point value, then click 'hit' to draw another random card from the deck. ...

What is the most efficient method to handle processing of all CSV files within a specific file directory using StreamReader?

I am currently facing an issue with my C# program that is designed to process CSV files. Initially, the program was functioning properly when I specified a single file. However, when I attempted to modify it to handle all CSV files within a designated di ...

Tips on utilizing the input tag inside a table - ensuring that the table td spans the entire width of the

Looking to integrate input tags into a table without borders around the input fields. <table class="table table-bordered"> <thead> <tr class="bg-info"> <th ...

Emulate an AngularJS ng-click action

My website has HTML code with three buttons: <button ng-click='showStats(player.data,0)'>Death Match</button> <button ng-click='showStats(player.data,1)'>Champions Rumble</button> <button ng-click='sho ...

Creating a Vue component using v-for and a factory function allows for dynamic

I am currently developing a Table component using factory functions for all logic implementation. Within a v-for loop, I generate a cell for each item in every row. The factory Below are the actual factories that I import into the respective vue page whe ...

Prevent selection duplication in adjacent select by disabling the option in AngularJS ng-options

In my table, I have 2 select options that change dynamically. <tr> <th>Start time</th> <th>End time</th> </tr> <tr ng-repeat="s in config.time"> <td> <select ng-model="s.start_time" ...

The passage of time becomes distorted after a few hours of using setInterval

I created a simple digital clock using JavaScript to show the time on a TV screen. However, after several hours of running, I noticed that the displayed time gets off by a few seconds (around 30 or more). Below is the code snippet I used: getTime() { ...

Is there a way to change the color of the menu button to white if the points are not visible?

I have created CSS to style the menu's color and make the buttons change color based on different actions. However, I also want the buttons to match the colors of the points on the map. To achieve this, I set the background color in JavaScript when ge ...

Implement a new aggregate function for tooltips in the Kendo chart

I am currently utilizing a kendo chart with a date x-axis. Each point on the graph corresponds to different dates, but the x-axis displays only a monthly view. To showcase the last data point for each month, I have implemented a custom aggregate function a ...

Retrieving additional parameters from an HTTP request

Imagine a scenario where I am sending a request to a Node Server in order to retrieve a JS file: <script src="/example.js" id="123456"> On the Node server side: app.get('/example.js', function(req, res, next) { console.log(req.params.id) ...

The auto-complete feature on Yahoo search occasionally displays outdated search suggestions

When using Yahoo Autocomplete with a remote php database request and zero time delay, I sometimes encounter the issue of old query results coming back after the most recent query. For example, if I search for "beginner", the results from "beg" may override ...

Top method for invoking handlers with nearly identical signatures

public class Config { static Dictionary<int, IHandler handler> dictionary = new Dictionary<int, IHandler>() { { 0, new Handler() }, { 1, new Handler() }, { 2, new SecondHandler() } }; public static IHandler ...

Error encountered: In ExtJS 4, a type error is being displayed stating that the URL is undefined

I have a scenario where I am creating a combo box using ExtJS 4 within an editable grid, and instead of using an ExtJS proxy, I am making an external AJAX call to populate it. The reason behind this approach is that I am using the same call to load other c ...