首页 > 解决方案 > Ajax-Call 从 Asp.Net MVC 中的控制器(返回 IList)获取 JSON 结果总是错误

问题描述

我正在尝试进行 AJAX 调用(Javascript),以便IList在控制器方法中创建一个。

index.js:

function getList() {
    $.ajax({
        url: myUrl, 
        type: "GET",
        dataType: "json",    
        success: function (response) {
            if (response) {
                //do sth
            }
        },
        error: function (response) {   
            alert("error");  //always error
            console.log(response); //object with just default functions
        }
   });

}

MyController.cs:

 public IList<SomeItem> loadList()
 {
        var items = db.SomeItemSet.Include(item => item.Sth).ToList();

        IList<SomeItem> resultList = new List<SomeItem>();

        for (int i = 0; i < items.Count(); i++)
        {
            //if(condition)
               resultList.Add(items[i]);                  
        }
        return resultList;
}

public JsonResult loadListJson()
{
    return Json(new { response = loadList() }, JsonRequestBehavior.AllowGet);
}

Controllermethod 中的断点显示它已执行。该列表不为空。

我还尝试将该方法声明为 Action Result(返回没有 jsonreqbehaviour 的 json)并在 ajax-Call 中执行 type: POST。你认为这里可能会失败吗?

网络调试面板显示代码

302:找到

(但不是 200:OK)尝试加载 ListJson 时。

例外:

System.InvalidOperationException:在序列化“System.Data.Entity.DynamicProxies.SomeItem_9D..”类型的对象时检测到循环引用。在 System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember)
在 ...

标签: c#jsonlistmodel-view-controllerasp.net-ajax

解决方案


您的对象结构中似乎存在循环引用。JSON 序列化程序不支持它。试试Select()方法。像下面的东西。

 var items = db.SomeItemSet.Include(item => item.Sth).Select(s=> new SomeItemDto{
 // which properties you need
}).ToList();

推荐阅读