c# - 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)
在 ...
解决方案
您的对象结构中似乎存在循环引用。JSON 序列化程序不支持它。试试Select()
方法。像下面的东西。
var items = db.SomeItemSet.Include(item => item.Sth).Select(s=> new SomeItemDto{
// which properties you need
}).ToList();
推荐阅读
- c# - LINQ select List where sub-list all items contains another list
- docker - 有人能解释一下第 5 行是什么意思吗?即添加。$HOME_DIR 在 docker 文件中是什么意思?
- reactjs - Typescript/React useRef 错误:(属性)React.RefObject
.current: HTMLFormElement | 空对象可能是“空”.ts(2531) - algorithm - 查找矩形的缺失坐标
- bluetooth-lowenergy - 低功耗蓝牙的传输功率是 Android 可配置的吗?
- ssl - 使用 cloud_proxy_sql 设置自定义 CA 证书
- java - 如何使用数组创建扫描仪并在 java 中找到输入用户的最小值、最大值和平均值?
- python - 在谷歌云上部署 python 文件
- laravel - Laravel - 将查询放在自定义请求中的好习惯?
- java - 如何在构建的 pom.xml 中打印属性?