Sending JSON data back to the server using KeyValuePair in C#

My goal is to send my JSON list back to the POST method (EditCompanyReportField) on the C# server side. The related parameter (fieldSorted) in my method is an array object, but the values are not being passed through. I have a few question marks regarding this.

Is KeyValuePair a struct and not a primitive type? Is that why?

Do I need to serialize the JSON object?

Also, I prefer not to create a model class for it.

Here is the back-end method:

public void EditCompanyReportField(IEnumerable<KeyValuePair<int, int>> fieldSorted)

Client-side JavaScript code:

var fieldSorted= [];
for (var i = 0; i < $scope.reportfield.length; i++) {
    fieldSorted.push({ Key: $scope.reportmapfield[i].MappedFieldId,
        Value: $scope.reportmapfield[i].IndexNo = i + 1 });   
};

$http({
    method: 'post', url: '/mapped/editcompanyreportfield',
    data: { fieldSorted: fieldSorted }
}).success(function () {
    $state.go("list-report");
    toastr.success(infoMessage.success);
});

The fieldSorted parameter on the back-end shows:

[0] {[0,0]} 
[1] {[0,0]} 
[2] {[0,0]} 

Thank you in advance...

Answer №1

Based on my assessment, your JavaScript code appears to be in good shape.

In the MVC setup, it typically anticipates data to be sent as serialized form parameters, which seems to differ from your current approach. Have you ensured that the content type of your AJAX request is set to "application/json"?

Answer №2

Encountered a similar issue when attempting to serialize data back into a List< KeyValuePair< int, bool>>. The result was:

[0]  {[0,false]} 
[1]  {[0,false]} 
[2]  {[0,false]} 

To resolve this, I switched to using Dictionary< int, bool > without affecting the data being posted back in JavaScript, and it started functioning correctly.

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

Error encountered while attempting to define a method in a class component in React.js

Can you tell me if these two code snippets are equivalent? async onSearchSubmit(term) { const response = await axios.get('https://api.somewebsite.com/search/photos', { params: {query: term}, headers:{ ...

"Utilizing FileReader to seamlessly integrate data into FormData without the risk

Currently, I'm in the process of constructing an ajax file uploader. This is made possible thanks to the recently introduced FormData interface. Everything seems to work as expected when using the original file. However, I encounter issues when conver ...

How can I translate these JQuery functions into vanilla JavaScript?

I am currently in the process of building a configurator using transparent images. The image configurator functions through a basic JQuery function: I have assigned each input element a data attribute called data-Image. This function identifies the data-Im ...

Receiving an error of "undefined" when trying to capture the selected

One issue I am facing is capturing the selected user option and sending that value in a post request. Let's put aside the post part since it's not directly related to the main question at hand. Currently, the value is showing up as undefined. ...

Exploring a JSON object within an AJAX request loop

Controller method: def get @projects = Project.get(params[:username]) render json: @projects.to_json end The JSON object returned by this controller method is passed as an array to the Ajax call shown below Ajax call : endpoint = ROOT_PAT ...

The form submission feature is malfunctioning due to JavaScript issues

I have forms that allow file uploads (images), and I am trying to restrict the size of those images to 500KB. However, for some reason, the forms are not submitting and I am unsure why. Below is the jQuery code: $('form').on('submit', ...

Javascript's associative arrays: a versatile tool for data organization

Is there a way to achieve the same functionality in JavaScript as this PHP code?: $this->gridColumnData[] = array('field' => 'id', 'width' => 50, 'title' => 'Enquiry Id') ; $this->gridColumn ...

Acquiring JSON data in PhoneGap for Android

Embarking on my journey with PhoneGap and Android, I find myself puzzled by the need to choose a specific platform when it's supposed to be cross-platform. My goal is to call a RESTful service, receive JSON data in response, and display it on the scre ...

Guide to inspecting file contents with Node.js

I am working on viewing the content of a file that is posted from the client using the fs module. However, with the code below, the contents are coming up as undefined. Can anyone help me identify what is missing in the code? To ensure I am receiving the ...

Leverage Vue.js to utilize dropdown selected data

I need help with populating additional form elements based on the selection of a record from a dropdown menu that contains response data obtained through an axios request. <multiselect v-model="order.orderJCname" id="orderJCname" name="orderJCname" :op ...

Checkbox click event not triggering properly

I am facing challenges in triggering an onclick event for the "Elevation" checkboxes located at the URL provided above. <input type="checkbox" value="A" id="elevation_A" onclick="changeElevation(this.value);" /> For some reason, the "changeElevati ...

Obtain the numerical value of the vertical position of the mouse (

Currently, I am coding a JavaScript game and my objective is to designate a variable specifically for the Y axis of the mouse. I kindly request that the code be kept as simple and straightforward as possible, avoiding unnecessary complexity. That conclud ...

Exploring various templates with AngularJS Directives

Let's delve into a slightly complex topic, but I'll simplify it as much as possible for you. There is a directive in play: .directive('configuratorRows', function () { return { restrict: 'A', scope: { ...

How to add a jQuery function to a Rails 3 if statement?

I followed a Rails 3 tutorial on creating a multi-step form which you can check out here. Additionally, I incorporated Stripe payment functionality in my app using another railscast found here. Within my application, the payment form is hidden using jQuer ...

Using NGRX Effects to Load Data for a Specific Item in Angular

On my website, there is a page that displays a range of products from the store managed by a reducer called products. When an action PRODUCTS.LOAD_ALL is dispatched, it triggers an API call through an effect and then sends a PRODUCTS.LOAD_ALL_SUCCESS actio ...

Comparison Between React-Redux mapStateToProps and Inheriting Props from ParentsIn the

Excuse my lack of experience, but I am currently delving into the world of react-redux and trying to grasp the concepts as I progress. Situation: In my main component within a react-redux application, I have the following snippet at the end: function map ...

Exploring the functionality of the onblur HTML attribute in conjunction with JavaScript's ability to trigger a

How do the HTML attribute onblur and jQuery event .trigger("blur") interact? Will both events be executed, with JavaScript this.trigger("blur") triggering first before the HTML attribute onblur, or will only one event fire? I am using ...

Is there a way to turn off the auto-complete feature for JavaScript keywords in HTML within JSX in WebStorm?

While using WebStorm, I've noticed that it automatically completes JavaScript keywords as I type regular text in JSX. This behavior is starting to frustrate me because I have to constantly press ESC or click elsewhere to hide the auto-complete popup. ...

Combine large arrays

Hey, I'm encountering some issues while trying to merge large arrays in a React Native app. Specifically, I am attempting to implement infinite scroll on React Native. The issue arises when the array reaches 500+ items; every time I add more items, my ...

Encountering a npm error E404 when trying to install unicons package for React development

I recently started working on a weather app project using create-react-app and encountered an issue while trying to install unicons for the project. Despite attempting a few solutions, I was unable to resolve the problem. Here is the command I used for th ...