我在我的 MVC 4 项目中将我的 JSON 数据发布回我的 api 控制器时遇到问题。这是我的javascript:
self.saveInvestment = function () {
var investmentdata = ko.mapping.toJSON( { "InvestmentSummary": self.InvestmentSummary } );
$.ajax({
url: "../api/investment/",
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: investmentdata,
success: function () {
alert('hi');
}
});
};
这是我的控制器代码:
[HttpPost]
public void Post([FromBody]InvestmentSummary val)
{
string blah;
if (val.InvestmentDetails[0] != null)
blah = val.InvestmentDetails[0].Cost.ToString();
}
这是来自提琴手的标题信息:
application/json; charset=UTF-8
http://localhost:1961
http://localhost:1961/Investment
X-Requested-With: XMLHttpRequest
POST http://localhost:1961/api/investment/ HTTP/1.1
Host: localhost:1961
Connection: keep-alive
Content-Length: 2470
Origin: http://localhost:1961
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11
Content-Type: application/json; charset=UTF-8
Accept: */*
Referer: http://localhost:1961/Investment
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
{"InvestmentSummary":{"InvestmentDetails":[{"Cost":"11","FairValue":0,"Tranches":[{"IDTranche":null.......
JSON 格式正确,我用 JSON Lint 仔细检查了一遍。当我在我的控制器中调试我的应用程序时,“val”中没有数据。我究竟做错了什么??谢谢!
编辑:这是我对 InvestmentSummary 的类定义:
public class InvestmentSummary : TransactionSummary
{
public InvestmentSummary()
{
this.InvestmentDetails = new List<InvestmentDetail>();
}
public List<InvestmentDetail> InvestmentDetails { get; set; }
}
我认为我的问题是我的 JSON 正在使用 InvestmentDetails,但我的类名是 InvestmentDetail?任何人,请帮忙?谢谢
第二次编辑* 我的完整 JSON 具有以下结构:
var init = {
InvestmentSummary: {
InvestmentDetails: [],
IDTransactionSummary:null,
TxnParameter: {},
TxnDate: "",
Fund: {},
PortfolioCompany: {}
}
};
在 tpeczek 的帮助下,我能够阅读 InvestmentDetails。但是现在我怎样才能得到我的 JSON 的其余部分呢?在我的 javascript 中,JSON 是正确构建的,但是,当它到达我的控制器时,只有 InvestmentDetails 存在。InvestmentSummary 的所有其他子项都消失了!谢谢