我的应用程序中有一个 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 服务仅显示空值。
这是调用 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/