【发布时间】:2014-07-01 22:08:04
【问题描述】:
我在 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;
}
我从一些 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
}
});
}
但结果是数组中除了第一个元素之外的所有内容都是未定义的:
string_field int_field
--------------------------
"7" 7 //data[0]
undefined undefined //data[1]
undefined undefined //data[2]
... ... //...
当我设置断点并查看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]
....
谁能解释这是为什么以及如何解决它?
GET 方法的返回类型会不会有问题?
我不应该使用getJSON吗?
感谢任何帮助。
【问题讨论】:
-
在返回数组之前在 C# 代码中放置一个断点。所有元素都有值吗?
-
是的,我做到了。 C# 中的数组在返回之前是完全正确的。
-
在浏览器开发工具中,你能看到正在发送的 JSON 是否包含这些值吗?如果这是服务器端或客户端,则需要缩小范围。
-
不,发送的 JSON 就像我在调试器中看到的一样。只有第一个元素具有带值的字段,其余元素完全缺少该字段。
-
好的,那可以专注于服务器端了。不幸的是,没有发现任何明显的问题。
标签: c# javascript entity-framework asp.net-web-api