tips for getting two ajax json Data from .net

When working with .NET, I am encountering an issue where I need to send two sets of JSON data (test1 and test2) to a .NET controller using JavaScript (ajax). Here is the code snippet for sending the data:

.ajax({
        type: 'POST',
        url: "/test/test_Put/",
        contentType: 'application/json; charset=utf-8',
        data: {json_1:JSON.stringify(test1), json_2:JSON.stringify(test2)},
        dataType:'JSON',
        success:function(data){
        },
        error: function (data) {
        }
    });

The code for the .NET controller handling this request looks like this:

[HttpPost]
public JsonResult test_Put([FromBody]test1 tt1, [FromBody]test2 tt2){
}

However, I am facing errors in implementing this approach. How can I effectively handle this scenario in .NET?

Answer №1

It is recommended to only use 1 [FromBody] attribute in your action method. https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-2.1

According to ASP.NET Core MVC guidelines, each action should have at most one parameter decorated with [FromBody]. This ensures that the request stream is properly read by the formatter and avoids conflicts when binding multiple [FromBody] parameters.

Consider creating a specialized wrapper class for handling such scenarios.

public class TestRequest
{
    public test1 json_1;
    public test2 json_2;
}

[HttpPost]
public JsonResult test_Put([FromBody]TestRequest data){}

Additionally, remember to adhere to camel case naming conventions for methods and variables in your code.

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

What is the method for invoking a function with arguments within an HTML `<p>` element?

I am looking to display like and dislike percentages on cards. <v-card v-if="software[2] == searched || searched == ''" class="software-card" > <h3>{{ software[2] }}</h3> ...

Error: JSON parsing failed due to an unexpected token 's' at position 1

I am currently developing a plugin and facing an issue with updating post meta in Wordpress. I have created a PHP code to handle this task by receiving an array/object/json array: public static function save_settings_fields(){ $myArray = json_decode( ...

Managing jquery values with cookies for loading, saving, and resetting

I recently implemented screen adjustments on my website using scrollbars. I utilized this example as a reference. Below is the code snippet... HTML CODE: <h1>Image Editor with CSS Filters and jQuery</h1> <!--Form for collecting image URL ...

Duplicate request submissions in ExtJs causing inefficiency

Trying to resolve an issue with my ExtJs table that handles remote filtering, sorting, and paging of data on the server. The problem arises when a default request is being sent alongside every other request: localhost/request?page=1&start=0&limit= ...

Top method in Angular 6 for verifying if a scrollable section has been scrolled to the very bottom

I am searching for a reliable solution in Angular 6 to determine whether a scrollable host component has reached its maximum scroll bottom. Despite my efforts, I have been unsuccessful in finding a functioning example of a function that can detect if a cu ...

Is there a way to automatically override the CSS cursor style?

Issue with SCSS styling on image link I attempted to modify the cursor style from pointer to default, but after saving and reloading my React app, the change did not take effect. I tried writing some code, but it seems that Stack Overflow is indicating an ...

Is it possible to capture key events within a frame even when the source differs?

I'm having trouble setting up a keydown listener on my page. The issue is that there's an iFrame within the page, and whenever I click inside it and press a key, the handler doesn't work. I've tried different methods from online resourc ...

`Inconsistencies between Postman and AngularJS service responses`

When I make a call to the endpoint using Postman, I receive this response: https://i.stack.imgur.com/pH31G.png However, when I make the same request from my AngularJS service defined below: this.login = function (loginInfo) { return $http({ ...

Regular expressions: understanding greedy versus lazy quantifiers

Imagine this situation: a = 'one\\two\\three.txt'; The desired output is "three.txt". However, the attempted solution of: a.match(/\\(.+?)$/) is unsuccessful. What could be causing this issue? How can we successf ...

Browserify - combine external modules into a single bundle

I am a complete beginner in the world of browserify. I recently discovered this interesting module called peer-file, which allows for file transfer between two browsers. After reading the Usage section in its readme, I realized I needed to include the scri ...

Having difficulty sending Crypto JS encrypted data through an ajax request

I am attempting to secure a password by encrypting it and saving it on Mongo LAB through an Ajax post call. Unfortunately, I am encountering the following error: I have tried looking up the error message but I'm unable to understand why it is pointin ...

What is the best way to create a continuous loop of images on a never-ending

Many discussions cover similar topics, but I have not yet found a solution to my specific question. Currently, I am working on creating a model for a website and I am interested in incorporating an infinite rotating gallery with a limited number of images ...

Getting js.map Files to Function Properly with UMD Modules

I am experiencing an issue with debugging TypeScript files in Chrome and Firefox. Specifically, when trying to debug the MapModuleTest.ts file, the debugger seems to be out of sync with the actual JavaScript code by two lines. This discrepancy makes settin ...

The battle between overwriting and allocation/deallocation for efficiency

I am developing a C++ application that will utilize a 1000-byte block of memory as a temporary buffer for text processing, which may occur up to 10,000 times per second. Can anyone verify if it is more cost-effective to allocate memory each time I need th ...

Unable to specify a default selection in Select2 multiple

After retrieving data through ajax and populating the select element with it, I am facing the challenge of setting default selections. How can I accomplish this task? Below is the code snippet for my ajax implementation: var productLists =[]; $.when(http ...

Using Three.js to extract Vertex Colors based on the z-coordinate of Vectors

Here is a sample: http://jsfiddle.net/c3shonu7/1/ The code demonstrates the creation of a BufferGeometry object by cloning an IcosahedronBufferGeometry's vertices. The goal is to apply a color gradient to the subdivided icosahedron, with lighter shad ...

Stop aspx button postback on click using cSharp

The following HTML code snippet includes an <asp:Button> element. <asp:Button ID="CalculateG481" runat="server" Text="Calculate" OnClick="CalculateG481_Click" /> When clicked, the button calls the function CalculateG481_Click but then initia ...

How come I keep running into the "is not a function" issue when trying to use the generateRequest function with Polymer's iron-ajax

Oops, it seems like there was an error: Uncaught TypeError: this.$.ajax.generateRequest is not a function. The issue seems to be in assets-ajax.html at line 23. <dom-module id="assets-pull"> <style> </style> <template> <but ...

Tips for displaying a loader image with a centered message and preventing the bootstrap modal dialogue box from closing during an AJAX response from a PHP file

I am using Bootstrap version 3.0.0. Below is the HTML code for a Bootstrap Modal: <div class="modal fade" id="newModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> < ...

Steps for inserting a JSON Array into a database

I have a dropdown menu that displays different options based on the selection from another dropdown. The data for each dropdown is fetched from the database and I need to insert the selected values into a new table in the database. All the necessary code ...