JavaScript array loading failed for the C# web service

I am encountering an issue with a JavaScript object in my application that contains an array object, which is a collection of objects with two properties (Name, Value) on the server-side.

Despite my efforts, when the code reaches the C# web service, the CustomProperties object is an array of 4 objects, but each Name and Value property is null.

myObject.CustomProperties = [];

myObject.CustomProperties.push({ Name: "FirstName", Value: $scope.userInfo.FirstName });
myObject.CustomProperties.push({ Name: "LastName", Value: $scope.userInfo.LastName });
myObject.CustomProperties.push({ Name: "Email", Value: $scope.userInfo.Email });
myObject.CustomProperties.push({ Name: "PortalId", Value: portalId });

I have also attempted the following...

myObject.CustomProperties = [];

myObject.CustomProperties.push({ "Name": "FirstName", "Value": $scope.userInfo.FirstName });
myObject.CustomProperties.push({ "Name": "LastName", "Value": $scope.userInfo.LastName });
myObject.CustomProperties.push({ "Name": "Email", "Value": $scope.userInfo.Email });
myObject.CustomProperties.push({ "Name": "PortalId", "Value": portalId });

Although all variables have values in the debugger, the array is not loading correctly, resulting in the web service showing null values.

https://i.sstatic.net/3a1zT.png

Below is the code that invokes the web service. I have removed what I believe to be unnecessary parts.

factory.callPostService("ActionName", myObject)
    .success(function (data) {
        // nothing happens inside this block
    })
    .error(function (data, status) {
    // this block always executes
        $scope.HasErrors = true;
        console.log("Unknown error occurred calling ActionName");
        console.log(data);
    });

The server-side code I am using closely resembles my other classes and properties.

Here is the property declaration for the CustomProperties in myObject.

public List<CustomPropertyInfo> CustomProperties { get; set; }

And here is the CustomPropertyInfo class.

[Serializable]
public class CustomPropertyInfo : ICustomPropertyInfo
{
    public string Name { get; set; }
    public string Value { get; set; }
}

Answer №1

The problem arises due to the Json Serializer not understanding how to properly deserialize the collection. To solve this issue, simply add Json attributes to the CustomPropertyInfo class in order to instruct Json.Net on how to handle the object. This will prevent any confusion when serializing or deserializing a generic List.

[Serializable]
[JsonObject(MemberSerialization.OptIn)]
public class CustomPropertyInfo : ICustomPropertyInfo
{
    [JsonProperty("Name")]
    public string Name { get; set; }

    [JsonProperty("Value")]
    public string Value { get; set; }
}

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

Retrieve data from MongoDB using the unique identifier (_id) and additional conditions with Express

Below is the code I am currently working with: PostCategory.find({categoryid:category._id.str},function(err,postcategories){ if(err) return next(err); Post.find({_id:postcategories.postid},function(err,posts){ if(err) ...

Backend communication functions seamlessly within the service scope, yet encounters obstacles beyond the service boundaries

I'm facing an issue with accessing data from my backend. Although the service successfully retrieves and logs the data, when I try to use that service in a different module, it either shows "undefined" or "Observable". Does anyone have any suggestions ...

Using LINQ to group and organize data to generate a series for a chart

Consider a simplified Items entity, which includes the following properties: Id (int, PK), itemDate (datetime, not null), and itemCategory (string, not null). Can you provide a LINQ to Entities query that calculates the total number of items in each categ ...

When data is stored in Internet Explorer's cache, any changes made are not being reflected in

Internet Explorer stores data in cache and even if there are changes, it may not reflect onclick. However, when I open the developer mode and try to access the same, then it works perfectly. This issue only seems to occur in IE as all other browsers work f ...

Is there a way to attach a hidden input to the file input once the jquery simpleUpload function is successful?

Attempting to add a hidden form field after the file input used for uploading a file through the simpleUpload call. Here is the HTML (loaded dynamically): <div class="col-md-6"> <div class="form-group"> ...

Grab the code snippet from JSFiddle

I apologize for the seemingly simple question, but I have been struggling with it. I tried looking at similar questions, but I couldn't find a solution. Despite copying the code from http://jsfiddle.net/sB49B/21/, I can't seem to get it to work ...

Typescript Array does not adhere to correct data type

Why does the code below fail to transpile when pushing a new instance of class B into an array that is typed as only accepting instances of class A? class A {}; class B {}; const arr: A[] = []; arr.push(new B()); ...

Currently, I am compiling a list of tasks that need to be completed, but I am encountering a dilemma that is proving difficult to resolve

Recently delved into the world of Javascript and encountered a roadblock that I can't seem to overcome. Here's the snippet of code causing me trouble: add = document.getElementById("add"); add.addEventListener("click", () => { console.log("Ple ...

Executing a conditional onClick function when the page loads

I have implemented a php-based authorization system that loads different authorization levels into a JavaScript variable. My goal is to disable certain onclick events based on the user's authorization level. I've come up with the following code ...

Tips for identifying and extracting various duplicates from a given list

I am presenting a list of various objects: ConnectionType = ConnectionType.COM ComPort = "com1" TcpPort = null ConnectionName = "CONN0" ConnectionType = ConnectionType.COM ComPort = "COM1" TcpPort = null ConnectionName = &quo ...

Unable to locate the specified view within AngularJS framework

<!doctype html> <html lang="en" ng-app="phonecatApp"> <head> <script src="/js/angular-1.5.2/angular.js"></script> <script src="/js/angular-1.5.2/angular-route.js"></script> <script src="/js/app.js">< ...

"Exploring the power of JQuery in adding new elements and accessing the newly appended

I have a code that appends some HTML to a div using JQuery like this: $("#divId").append("<div class='click' data-id='id'></div>"); and I want to access the appended div by clicking on it like so: $(".click").click(functi ...

Tips for incorporating a list into a MongoDB query

I encountered a problem with my dynamic queries when using an array for the column value. For example, if col is an array like c("red", "blue"), the query fails to execute. Works fine with single value col<-"red" pipe1 <- paste("{&bsol ...

Issue with Angular not sending data to ASP.net server

Attempting to send data to my asp.net server using angular. After testing the front-end data, the issue arises when sending the data with a post request; angular sends null data instead. Interestingly, when sending the same data to the server from Postman, ...

Unveiling all Gatsby.js routes/endpoints in Cypress tests: A comprehensive guide

I am currently in the process of creating end-to-end tests with Cypress for a project built on Gatsby. One specific test requires me to iterate through all pages of my Gatsby site. To accomplish this, I require a test fixture (such as endpoints.json) cont ...

Complete a bootstrap row and begin a new row after every nth div element

I have a grid layout in Bootstrap that I will be filling with blog post thumbnails. <section class="container"> <div class="row thumbs"> <div class="col-sm-3">content</div> <div class="col-sm-3">content</div> ...

Unable to update due to outdated response call causing issues

I am currently in the process of updating outdated response calls and have encountered a peculiar issue where the response is not being properly ended. Typically, I would use : res.send(200, {message: 'Location Updated'}); However, this method ...

The scrollview is interactive and can be scrolled by hovering the mouse over the content

I implemented a Scrollview around a textlabel and it seems to be functioning well. However, I noticed that I can only scroll when the mouse is directly over the scrollbar. Is there a way to enable scrolling even when the mouse is positioned over the conte ...

The function Router.push("/") is not functioning as expected when called within the pages/index.js file

Currently, I'm utilizing the Next JS next-auth/react library and aiming to direct authenticated users straight to the dashboard. Here's a snippet from my index.js file: import { useRouter } from "next/router"; import Link from "nex ...

Building a table using jQuery and adding elements using JavaScript's append method

Greetings! I've been attempting to add new records from a form that registers or updates student information, but unfortunately it doesn't seem to be functioning correctly. Can anyone point me in the right direction as to why this may be happenin ...