【问题标题】:Javascript array of objects to MVC action barely working, but not fullyJavascript 对象数组到 MVC 动作几乎不能工作,但不完全
【发布时间】:2016-06-06 02:14:23
【问题描述】:

我正在尝试通过 ajax 将 javascript 对象数组传递给 MVC 操作;这是我的代码:

阿贾克斯:

$.ajax({
   type: "POST",
   url: rv + "ajxConversation/wrcrgmdisc",
   dataType: "json",
   traditional: true,
   data: JSON.stringify(pllst),
   contentType: "application/json",
   async: true,
   global: false,
   cache: false,
   success: function (d) {
     //Whatever
   }
});           

MVC:

public JsonResult wrcrgmdisc(List<DCConvGmPlayersDisc> pllst)
{
}

[DataContract]
public class DCConvGmPlayersDisc
{        
   [DataMember]
   public string clr = "";

   [DataMember]
   public string tlt = "";

   [DataMember]
   public string fnm = "";

   [DataMember]
   public string lnm = "";
}

现在,我的问题是,在 MVC 方面,它似乎接收到一个包含所有项目的数组,但它们都有空属性,而不是空属性:如果我发送一个包含 5 个项目的 JS 数组,我的 pllst 计数在 MVC 端是 5,但每个项目的每个属性都是空的:在调试模式下的服务器端,我看到 pllst[0].clr 是一个空字符串,pllst[0].tlt 是空的,等等...... .

Here's a screen shot of JS "alert(JSON.stringify(pllst));" to prove you that I'm not passing an empty array: sdfsd

...and one from the server side showing that the received array really has 3 items, but all properties are empty

谁能告诉我一种通过 Ajax 或页面链接将 Javascript 对象数组(不是字符串数组或 int 数组,例如 int[] 变量)传递给 MVC Action 的 FUNCTIONNAL 方式这表明了这一点:我在整个网络上搜索了一个功能齐全、简单、标准的方式(这不是标准的 Ajax:$.get('/controller/MyAction', { vals: arrayOfValues }, function (data) {. ..} ) 这样做,我还没有找到一个,即使在 Stackoverflow 上也是如此!

感谢

【问题讨论】:

  • 您需要编辑问题以显示pllst 是什么
  • 是的。图片很烂。提供文本真的很容易,而且整个负载更容易理解。
  • 你的模型只有字段,没有属性({ get; set; })所以DefaultModelBinder不能设置

标签: javascript arrays ajax asp.net-mvc


【解决方案1】:

您的DCConvGmPlayersDisc 类只有字段,没有属性,因此DefaultModelBinder 不能设置 值。将您的班级更改为

public class DCConvGmPlayersDisc
{        
    public string clr { get; set; }
    public string tlt { get; set; }
    public string fnm { get; set; }
    public string lnm { get; set; }
}

【讨论】:

  • 就是这样:我刚刚将我的字段更改为属性(抱歉混淆了字段和属性:大学理论对我来说已经很久了哈哈!)现在它工作正常......感谢斯蒂芬快速回答
  • 我建议您编辑您的问题以显示 pllst 是什么 包含代码图像是不可接受的,如果您不这样做,您的问题会随着时间的推移吸引很多反对票(另外我会删除我的反对票)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-10
  • 2012-01-08
  • 1970-01-01
  • 2013-01-12
  • 2012-12-20
  • 1970-01-01
  • 2014-06-24
相关资源
最近更新 更多