我在将我的JSON数据发布回我的MVC 4项目中的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();
}
这是来自fiddler的标题信息:
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的所有其他孩子都不见了! 感谢
答案 0 :(得分:1)
首先,您不应该将对象包装到JavaScript中的另一个对象中:
self.saveInvestment = function () {
var investmentdata = ko.mapping.toJSON(self.InvestmentSummary);
$.ajax({
url: "../api/investment/",
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: investmentdata,
success: function () {
alert('hi');
}
});
};
在这种情况下,您也不需要FromBody
:
[HttpPost]
public void Post(InvestmentSummary val)
{
string blah;
if (val.InvestmentDetails[0] != null)
blah = val.InvestmentDetails[0].Cost.ToString();
}