【发布时间】:2018-07-17 22:03:50
【问题描述】:
使用 AJAX 调用将数据从控制器传递到视图 但由于某种原因,我无法使用 JavaScript 检索它 数据显示空对象的列表!
public class Ville {
string wilPop { get; set; }// = null;
int identifiant { get; set; }// = -1;
bool affectedD { get; set; } //= false;
public Ville(string ewilPop, int eidentifiant, bool eaffectedD)
{
this.wilPop = ewilPop;
this.identifiant = eidentifiant;
this.affectedD = eaffectedD;
}
}
[Authorize]
[HttpPost]
public ActionResult GetWilByRegion(int? Wil)
{
if (Wil != null)
{
string wilPop = null;
int identifiant = -1;
bool affectedD = false;
//Get info from DB
List<city> ListWil = new List<city>();
ListWil = db.city.Where(m => m.idReg == Wil).OrderByDescending(m => m.population).ToList();
List<Ville> mylist = new List<Ville>();
foreach (city item in ListWil)
{
// Description in the DB
wilPop = item.city + " (" + item.population + ")";
// id value in the DB
identifiant = item.city_id;
// if checked or not
affectedD = CheckifWilAffected(item.city_id);
mylist.Add(new Ville(wilPop, identifiant, affectedD));
}
return Json(mylist, "Ville");
}
else return Json("Error");
}
mylist不为空,包含所有数据(调试控制器后)
这是我的 AJAX 调用:
$.ajax({
url: url,
data: { Wil: _idr },
cache: false,
type: "POST",
success: function (data) {
var markup = "";
for (var x = 0; x < data.length; x++) {
markup += '<input type=' + '"checkbox"' + ' name=' + data[x].wilPop + ' value=' + data[x].identifiant + '>' + data[x].wilPop + '</input>' + '<br/>';
}
$("#chWil").html(markup).show();
},
error: function () {
alert("Error - can't do the ajax call - please check your code..." );
}
});
}
【问题讨论】:
-
请edit您的问题并发布
Ville课程 -
将调试器附加到控制器。是返回数据吗?在 Fiddler 中观看 Ajax 调用。响应是否具有预期的格式和内容?将调试器附加到 javascript(Chrome 工具)。
data里面有什么吗? -
mylist 包含所有信息,但是当我将调试器附加到 java 脚本时,数据为空({}、{}、{}、{}、{}、{}、{} 列表)
标签: javascript c# json ajax asp.net-mvc