javascript - 无法加载 C# Web 服务的 JavaScript 数组

标签 javascript c# arrays angularjs asp.net-web-api2

我的应用程序中有一个 JavaScript 对象,它有一个数组对象,在服务器端,该对象是具有两个属性(名称、值)的对象的集合。

我确信我在这里错过了一些简单的东西,因为我已经盯着它看太久了,但是当以下代码将其发送到 C# Web 服务时,CustomProperties 对象作为 4 个对象的数组。但是,每个 Name 和 Value 属性均为 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 });

这个我也试过了...

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 });

上述所有变量在调试器中都有值,但数组一定不能正确加载,因为 Web 服务仅显示空值。

enter image description here

这是调用 Web 服务的代码。不过,我删除了我认为不必要的部分。

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

我使用的服务器端代码看起来与我的其他类和属性几乎相同。

这是我的示例中 myObject 的属性。

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

这是 CustomPropertyInfo 类。

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

最佳答案

导致该问题的原因是 Json Serializer 不知道如何正确反序列化集合。解决此问题的最简单方法是使用 Json 属性标记 CustomPropertyInfo 类,以告诉 Json.Net 如何处理此对象。这消除了因序列化/反序列化通用列表而引起的任何困惑。

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

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

关于javascript - 无法加载 C# Web 服务的 JavaScript 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33062021/

相关文章:

javascript - 使用按钮进行 Knockout 模板绑定(bind)

c# - 使用按钮从 GridView 和数据库中删除记录

java - 在使用 java 的 Rest-assured 执行操作时,无法获取断言的响应正文数据

c++ - 如何让 for_each 使用模板?

javascript - 使用 Angular 服务在 ng-view 页面之间共享数据

javascript - Playwright 中有没有办法在动态表中选择特定按钮?

javascript - Firebase Admin SDK GO VerifyIDToken 返回的不是 App Engine 上下文错误

c# - WinForms 线程间修改

c# - 原型(prototype)设计模式与 ICloneable

c - 为什么代码会用指针停止并中止执行?