【问题标题】:Can't pass a list of objects to the view using JSON无法使用 JSON 将对象列表传递给视图
【发布时间】: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


【解决方案1】:

您将获得一个空对象数组(没有任何属性),因为您的 Ville 类没有任何 public 属性。

您需要将您的属性设为public

public class Ville
{
    public string wilPop { get; set; }
    public int identifiant { get; set; }
    public bool affectedD { get; set; }

    public Ville(string ewilPop, int eidentifiant, bool eaffectedD)
    {
        this.wilPop = ewilPop;
        this.identifiant = eidentifiant;
        this.affectedD = eaffectedD;
    }
}

现在,JavaScript 序列化程序将能够在创建列表的 JSON 字符串表示时使用这些属性的值。

我个人喜欢使用 PascalC作为类属性名称。(WilPop 而不是 wilPop

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-04
    • 2021-09-19
    • 2016-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-22
    • 1970-01-01
    相关资源
    最近更新 更多