2011-01-19 74 views
0

我有一种情况,我想通过Ajax/JQuery传递记录列表。通过jQuery记录列表

public JsonResult GetListOfRecords() 
{ 
    return Json(_repository.GetAllRecords()); 
} 

当我把这种操作方法与jQuery,这是行不通的:

$.getJSON('GetAllRecords', function(data){ // data is IQueryable<T> or IEnumerabel<T> 
$.each(data, function(d) { 
    $('#somewhere').html(d.Title); //d is SomeModelType and Title is property of that type 
}); 
}); 

注:GetAllRecords方法返回的IQueryable ....我还测试IEnumerable的

但是,如果通过ArrayList类型,它似乎是工作(但不满足我的需要):

public JsonResult GetAllRecords() 
{ 
    var list = new ArrayList(); 
    foreach(var item in _repository.GetAllRecords()) 
    { 
    list.Add(item.Title); 
    } 
    return Json(list); 
} 

它只是显示标题...

我的问题是, “我想通过的IQueryableIEnumerable的通过Ajax。”

回答

1

这似乎并非如此。以下作品与IEnumerable<T>和匿名类型完美的罚款:

public ActionResult GetListOfRecords() 
{ 
    return Json(
     Enumerable.Range(1, 3).Select(i => new 
     { 
      Id = i, 
      Title = "title " + i 
     }), 
     JsonRequestBehavior.AllowGet 
    ); 
} 

和调用:

$.getJSON('<%= Url.Action("GetListOfRecords") %>', { }, function(records) { 
    $.each(records, function(index, record) { 
     alert(record.Id + ' ' + record.Title); 
    }); 
}); 

还要注意在$.each()功能轻微subtility。

在你的情况有:

$.each(data, function(d) { ... 

在我的情况,我有:

$.each(data, function(index, d) { ... 

回调的第一个参数是指数,而不是价值。

+0

OIC ...在jQuery我没有使用索引参数...它现在可能工作...谢谢 – 2011-01-19 10:14:14