【问题标题】:Data is array of objects passed to action through AJAX数据是通过 AJAX 传递给操作的对象数组
【发布时间】:2017-10-18 09:22:30
【问题描述】:

这里我可以通过 AJAX 将数据作为对象数组传递给控制器​​,但我在控制器端得到的值为 null。

var newData  = [{Code:"FT",Id:1:Year:2005,TypeId:1,Value:20},
                {Code:"FR",Id:2:Year:2006,TYpeId:3,Value:40},
                {Code:"FY",Id:3:Year:2007,TYpeId:5,Value:50}]


$.ajax({
    url: "api/FG/cretejson",
    type: 'POST',
   contentType: "application/json",
   data: JSON.stringify({ extraParams: newData }),
   success: function (data) {
       var result = result;
   }
});

public JsonResult cretejson([FromBody]List<rev> extraParams)
{
    try
    {

        return Json(new { Result = "OK", Options = extraParams });
    }
    catch (Exception ex)
    {
        return Json(new { Result = "ERROR", Message = ex.Message });
    }
}
public class rev
{
    public string Id { get; set; }
    public string Code { get; set; }
    public int TypeId { get; set; }
    public int Year { get; set; }
    public int Value { get; set; }
}

任何帮助将不胜感激。

【问题讨论】:

  • TypeId 在 JSON 和 c# 模型中都是 int。与Value 相同。那么为什么 Year 在 c# 模型中是 int 而在 JSON 中是 string
  • data: JSON.stringify({ extraParams: newData }) 这行将发送一个像extraParams={ YOUR JSON AS STRING} 这样的正文。请您尝试通过data: newData发送邮件
  • camilo,我错了,我们可以编辑它模型..
  • 卡米尔,请帮帮我..
  • Oguz Ozgu,我尝试这种方式但没有获得价值。

标签: c# mysql asp.net-core


【解决方案1】:

AJAX 调用:

 $.ajax({
       url: urlString,
       type: 'POST',
       data: sc,
       dataType: 'json',
       crossDomain: true,
       cache: false,
       success: function (data) { console.log(data); }
    });

Web API 控制器:

 [HttpPost]
 public string PostProducts([FromBody]List<SyncingControl> persons)
 {
    return persons.Count.ToString(); // 0, expected 3
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-09
    • 1970-01-01
    • 1970-01-01
    • 2012-08-27
    • 2015-03-01
    相关资源
    最近更新 更多