无法使用JSON将对象列表传递给视图

时间:2018-07-17 22:03:50

标签: javascript c# json ajax asp.net-mvc

使用AJAX调用将数据从控制器传递到视图 但由于某些原因,我无法使用JavaScript进行检索 数据显示了一个空对象的列表!

Image : what i see in my browser

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

1 个答案:

答案 0 :(得分:2)

由于您的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;
    }
}

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

我个人喜欢使用 P ascal C 作为类属性名称。(WilPop代替wilPop