简体   繁体   中英

Ajax-Call to get JSON Result from Controller (returning IList) in Asp.Net MVC always errors

I am trying to make an AJAX-Call (Javascript) in order to get a IList created in a Controller-method.

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);
}

A breakpoint in the Controllermethod shows me that it is executed. The list is not null.

I also tried to declare the method as Action Result (return json without jsonreqbehaviour) and doing type: POST in the ajax-Call. What do you think could fail here?

The network debugging panel shows the code

302:found

(but not 200:OK) when trying to loadListJson.

Exception:

System.InvalidOperationException: A circular reference was detected while serializing an object of type 'System.Data.Entity.DynamicProxies.SomeItem_9D..'. at System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember)
at ...

It seems that there are circular references in your object structure .It is not supported by the JSON serializer. Try Select() method. Something like below.

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

I used Newtonsoft.Json.JsonConvert to convert my list !

index.js:

function getList() {
    $.ajax({
        url: myUrl, 
        type: "POST", //
        dataType: "json",    
    success: function (list) {
        if (list) {
            //do sth 
        }
    },
    error: function (response) { //do sth }
   });
}

MyController.cs:

 public ActionResult loadListJson()
        {
            return Content(Newtonsoft.Json.JsonConvert.SerializeObject(loadList()), "application/json");
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM