[英]JavaScript array undefined when returned from ASP.NET Web API, GET method
I have the current GET method in C#: 我在C#中具有当前的GET方法:
public CustomObject[] GetSample(long id)
{
CustomObject[] arr;
var topt = new TransactionOptions();
topt.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
using (var tscope = new TransactionScope(TransactionScopeOption.Required, topt))
{
using (var context = new DatabaseEntities())
{
context.Database.Connection.Open();
/*STARTING HERE*/
var co =
from a in context.tableA /*... some query conditions*/
select new CustomObject()
{
int_field = a
};
//change co from IQueryable<CustomObject> to CustomObject[]
arr = co.ToArray();
for (var i = 0; i < arr.Length; i++)
{
arr[i].string_field = arr[i].int_field.intToString(); //a custom method that converts int to string
}
/*ENDING HERE*/
}
tscope.Complete();
}
return arr;
}
I'm calling it from some JavaScript code: 我从一些JavaScript代码中调用它:
function doQuery(id) {
$.getJSON(somePath + '/GetSample/' + id)
.done(function (data) {
//data should be of type CustomObject[]
for (var i = 0; i < data.length; i++) {
appendToTable(data[i]); //this function displays each CustomObject in a table
}
});
}
But the result is that everything except for the first element in the array is undefined: 但是结果是除了数组中的第一个元素以外的所有东西都是不确定的:
string_field int_field
--------------------------
"7" 7 //data[0]
undefined undefined //data[1]
undefined undefined //data[2]
... ... //...
When I set a breakpoint and look at data
, the other fields are actually missing: 当我设置一个断点并查看data
,其他字段实际上丢失了:
data
[0]
__proto__
$id
string_field //has value of "7"
int_field //has value of 7
[1]
__proto__
$id //the other fields are missing
[2]
....
Can anyone explain why this is and how to fix it? 谁能解释这是为什么以及如何解决? Could the return type of the GET method be a problem? GET方法的返回类型可能有问题吗? Should I not use getJSON
? 我不应该使用getJSON
吗?
Any help is appreciated. 任何帮助表示赞赏。
Use response.data in callback function 在回调函数中使用response.data
function doQuery(id) {
$.getJSON(somePath + '/GetSample/' + id)
.done(function (response) {
//data should be of type CustomObject[]
for (var i = 0; i < response.data.length; i++) {
appendToTable(response.data[i]); //this function displays each CustomObject in a table
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.