2

I have a api controller function that returns an array of objects. The following is how I call my function and an example of what happens:

$.getJSON("/api/mycontroller/myfunc/?id=" + id, function (data) {
   data[0].field1  <- correct value here
   data[0].field2  <- correct value here

   data[1].field1  <- null
   data[1].field2  <- null
}

The first element contains the correct values as illustrated but all other elements are null. data.length returns the correct size of the array and I have verified that my controller is returning the values I anticipate. Am I missing something here???

UPDATE: Here is my controller method:

public data[] myfunc(long id)
{
     return db.MyTable.Where(x => x.ID == id).ToArray();
}  

As mentioned I have verified that the array being returned contains the correct values.

JSON response is this:

Object { $id="1",  Referral={...},  MeetingID=1,  more...}
$id     "1"
Referral    Object { $id="2",  IntakeMember={...},  Meetings=[3],  more...}
MeetingID   1
MeetingDate "2015-01-01T00:00:00"
Notes   "test1"
ReferralID  22

Object { $ref="16"}
$ref    "16"

Object { $ref="17"}
$ref    "17"

So as you can see elements 2 and 3 just have this "ref" value in them...not sure why??

UPDATE #2:

Tried $.get rather than $.getJSON without success, same issue. I also tried making the following changes to the controller:

MyData[] data = db.MyTable.Where(x => x.ID == id).ToArray();
JsonResult jsonResult = new JsonResult
{
    Data = data,
    JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
return jsonResult.Data;

I still experience the same issue.

4

2 回答 2

1

出于某种原因,当我在数据库中创建一个视图并使用它来返回数据而不是直接查询它所在的表时,我的问题得到了解决。我把这个听一下,以防有人遇到与我类似的问题,但如果有人知道为什么这发生了我很想听听......请评论这个答案。

于 2015-09-04T12:44:12.583 回答
1

$.getJSON()期望返回的数据是 JSON。更改控制器方法以返回 JSON

public JsonResult myfunc(long id)
{
     var data = db.MyTable.Where(x => x.ID == id);
     return Json(data, JsonRequestBehavior.AllowGet);
}  
于 2015-09-02T22:53:21.780 回答