【问题标题】:JavaScript array undefined when returned from ASP.NET Web API, GET method从 ASP.NET Web API、GET 方法返回时 JavaScript 数组未定义
【发布时间】: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


【解决方案1】:

在回调函数中使用 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
            }
        });
}

【讨论】:

    猜你喜欢
    • 2016-04-27
    • 2020-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-25
    • 1970-01-01
    • 2012-08-20
    • 1970-01-01
    相关资源
    最近更新 更多