传递给MVC Rest接口时,JSON Array为null

时间:2015-03-19 18:35:44

标签: c# arrays json asp.net-mvc http-post

我正在尝试传递一个JSON对象,该对象包含通用字符串属性和包含属性的对象数组。

模型对象:

public class Stock
{
    public IEnumerable<Daily> DailyList;
    public string Symbol { get; set; }
    public double PERatio { get; set; }
}

public class Daily
{
    public double EndOfDayPrice { get; set; }
    public int Volume { get; set; }
    public double DayDiff { get; set; }
}

以下是我的HomeController代码:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public JsonResult Dump()
    {
        Stock s = new Stock()
        {
            Symbol = "YHOO",
            PERatio = 4.31,
            DailyList = new List<Daily>()
            {
                new Daily {EndOfDayPrice = 4.13, DayDiff = 1.2, Volume = 15000 },
                new Daily {EndOfDayPrice = 4.1, DayDiff = .5, Volume = 1300 }
            }
        };

        return Json(s, JsonRequestBehavior.AllowGet);
    }

    [HttpPost]
    public JsonResult ProcessDataReturned(Stock stock)
    {
        stock = stock;
        // int count = mylist.Length;
        return Json("success");
    }
}

这是我页面上的JavaScript:

function calculate(pricelist) {
    var count = 1; //skip first;
    var teststring = { "DailyList": [{ "EndOfDayPrice": 4.13, "Volume": 15000, "DayDiff": 1.2 }, { "EndOfDayPrice": 4.1, "Volume": 1300, "DayDiff": 0.5 }], "Symbol": "YHOO", "PERatio": 4.31 };

    $.post("/home/ProcessDataReturned/", teststring).done(function (data2) { document.write(data2 + "<hr>"); });
    //Tried with the JSON.stringify also.
    $.post("/home/ProcessDataReturned/", JSON.stringify(teststring)).done(function (data2) { document.write(data2 + "<hr>"); });
}

当我转到控制器并观察来自DailyList数组的值始终为null。其他属性都很好。我试图使模型(C#)同时使用IList和IEnumerable属性。

贡献者建议的新代码。我仍然遇到同样的问题。数组仍为空(不为null,因为我在构造函数中初始化它)。

    var x = JSON.stringify({ stock: teststring });
    //Other variations I have tried
    //var x = JSON.stringify(teststring);

    $.ajax({
        url: '@Url.Action("ProcessDataReturned", "home")',
        data: x,
        type: 'POST',
        traditional:true,
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            $('#message').html("Reason was updated");}
    });

解决方案:因为实际上有多件错误我给了每个人一些信誉。另外我自己发现了一个bug。 我必须使用ajax调用的长格式版本。即使用$ .ajax而不是$ .post 2.我在服务器上的模型设置不正确。我需要添加&#34; {get; set;}&#34;到列表的属性声明。我的愚蠢错误和下面的代码让我看到了这个问题。     公共类股票     {         // public IEnumerable DailyList;         //将此更改为此(愚蠢的错误):         public IEnumerable DailyList {get; set;};         public string Symbol {get;组; }         public double PERatio {get;组; }     }

1 个答案:

答案 0 :(得分:1)

由于您的收集项目与索引器的名称不正确,因此您需要将ajax()traditional: true一起使用。

var teststring = { "DailyList": [{ "EndOfDayPrice": 4.13, "Volume": 15000, ....}
$.ajax({
  type: 'POST',
  url: '@Url.Action("ProcessDataReturned", "home")', // do not hard code your urls
  traditional: true,
  contentType: "application/json; charset=utf-8",
  data: JSON.stringify({ stock: teststring }),
  ....
})

请注意,您的javascript对象是

{ DailyList[0].EndOfDayPrice: 4.13, DailyList[0].Volume: 15000, ..., DailyList[1].EndOfDayPrice: 4.1, DailyList[1].Volume: 1300, ...}

然后使用代码中的$.post()方法绑定对象

修改

您的Stock类没有DailyList(其字段)的属性,因此默认模型绑定器无法设置值。将其更改为属性

public IEnumerable<Daily> DailyList { get; set; }