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

Unlocking the Magic of JSONP: A Comprehensive Guide

Currently attempting to utilize JSONP in order to work around Cross Domain challenges. I referenced this solution: Basic example of using .ajax() with JSONP? $.getJSON("http://example.com/something.json?callback=?", function(result){ //response data a ...

Can you iterate through each element that matches those in a different array?

As a beginner in Javascript, I may stumble upon some obvious errors, so please bear with me. My goal is to iterate through two arrays and perform a loop for each element that exists in both arrays. Currently, this is my code: if(obtainedCards.some( sp =& ...

The issue of req.file being consistently undefined in Node.js multer

I am having issues trying to upload a file using multer because the req.file is always undefined and the destination folder remains empty: Server: var express = require('express'); var multer = require('multer') var app = express(); ...

Import a JavaScript file with beneficial test functions for selenium testing

Utilizing the runScript command in selenium has proven to be incredibly helpful for me. I've been using it to calculate values within a table and then store the result like so: <tr> <td>runScript</td> <td>var cumulativ ...

SWR Worldwide Settings

I am trying to configure a global SWRConfig in my Next.js application. In my _app.js file, I have the following setup: import '@/styles/bootstrap.min.css'; import "@/styles/globals.css"; import Layout from "@/components/Layout"; import { SWRConfi ...

The complexity of JQuery's design has left many puzzled

I am new to using Jquery and I have come to the following realizations: Every selector in Jquery always returns a wrapped list of items, which can be: An empty list A list with a single element A list with multiple elements Chained functions operate o ...

The issue persists with UIkit modal element remaining in the DOM even after the parent component in Vue.js is destroyed

In my Vue app, I am utilizing the UIKit modal. UIkit.modal(element).show(); // This adds the class uk-open and sets style to display:block UIkit.modal(element).hide(); When I hide the modal, it simply removes the class uk-open and the inline style of dis ...

What is the best way to break down my node module into separate files?

I am currently in the process of organizing my node module functions by splitting them into separate files to accommodate numerous functions that need to be added. My objective is to call the main file's functions from files located within the lib di ...

What benefits does utilizing a liquid template in Azure Logic Apps offer when it comes to transforming XML data?

Converting XML to JSON in logic apps is as easy as calling json(xmlStringHere), so it begs the question: why would we need a liquid template? ...

What is the reason behind my difficulty in opening my dialog box modally using JavaScript?

I am looking to keep a dialog open while data is being fetched from the server. Here is the code I have written: (async()=>{ document.getElementById("dialog").showModal(); if(condition1 is true){ await server_call1(); } ...

A step-by-step guide to effectively stubbing a dependency within an express middleware using a combination of express-validator, mocha, chai, sinon,

**Edit: Re-created with a simple example that works first: I have an example file and two modules. moduleA has a dependency called moduleB // moduleA.js const ModuleB = require('./moduleB'); function functionA() { return 20 + ModuleB.functio ...

Issue with firing the React-Redux action has been encountered

I am currently utilizing React along with react-redux, redux and redux-actions. Within my application, I have a specific action that is responsible for verifying the validity of the token stored in localStorage to ensure it is not expired. This action loo ...

A guide to updating a particular row and sending parameters with jQuery and AJAX

I am utilizing a JSON response to dynamically display table content. Here is the code I am using to display row values: var rows = ''; for(var i=0; i<response.response.length; i++) { rows += '<tr><td class="country">&ap ...

Filtering multiple rows in a table using Javascript

I'm currently working on creating a filter that can filter based on multiple inputs, with each input filtering in a separate column. Here is the JavaScript & code I am using: function myFunction(column, input) { var filter, table, tr, td, i, t ...

Determine the image's position in relation to its parent element while factoring in any vertical offset

Within my HTML, I have arranged two images to sit adjacent to one another. Interestingly, one image happens to be taller than the other. Despite assigning a CSS property of vertical-align: middle to both images, the result is that the shorter image appears ...

Is there a way to set table column headers in ngGrid using values from another array?

The JSON I am working with is organized into 'headers' and 'rows'. For example: { "headers": ["id","timestamp from","blah1","blah2"], "rows": [["69517737","1416932540011285849","104220.00","170968251000.000: ...

Instructions for properly formatting a date extracted from ASPX JSON through AJAX

Recently, I have been extracting data from a MySQL database, converting it into JSON format, and using AJAX to display the data on a Chart.JS. However, there is an issue with the date values being formatted as: /Date(154564434687)/ Below is the JQuer ...

Can we enforce all DateTime properties to be represented as DateTime2 in the model?

Is it possible to set all DateTime properties in Entity Framework 6 Code First to be modeled as DateTime2 by default? I understand that I can use .HasColumnType("datetime2") to specify the data type for each individual DateTime property, but I'm c ...

Transforming various date formats into the en-US format of mm/dd/yyyy hh:mm:ss can be accomplished through JavaScript

When encountering a date format in en-GB or European style (mm.dd.yyyy), it should be converted to the en-US format (mm/dd/yyyy). If the date is not already in en-US format, then it needs to be converted accordingly. ...

The issue of appending request URLs in the $.ajax function

Can anyone explain why jQuery.ajax() adds a parameter to the URL? I enabled cache, but it's still not working as expected. The console logs are not showing up and the request URL is being modified with &_=1396146406542. How can I remove this add- ...