我正在尝试通过Ajax将List发送给我的acton。此刻,我正在为我的行动获取数据,但恢复的数据是胡言乱语,例如evrything是NULL,有5个元素,而不是一个。 我需要通过jquery收集数据,因为我想动态扩展这个列表。
我认为根本问题是我的JSON与我的行动期望的JSOn有所不同 - 但我是新手,并没有看到错误。发送给操作的JSON是:
{
"ideas": [
{
"name": "[0].ID",
"value": "1"
},
{
"name": "[0].Name.EnglishText",
"value": "New Idea"
},
{
"name": "[0].Name.GermanText",
"value": "Neue Idee"
},
{
"name": "[0].Description.EnglishText",
"value": "1"
},
{
"name": "[0].Description.GermanText",
"value": "1"
}
]
}
我尝试构建我的列表的JSOn版本,如下所示: 实际上完全不同:(
"[{
"ID":0,
"Name":
{
"EnglishText":"English",
"GermanText":"Ger"
},
"Description":
{
"EnglishText":null,
"GermanText":null
},
"Project":null
}]"
让我解释一下: 该网站如下:
<div id="collapseIdeas" class="panel-collapse collapse">
<div class="panel-body">
@for (int i = 0; i < Model.Count(); i++)
{
<div class="panel panel-default">
<div class="panel-heading">@Model[i].Name.GetText()</div>
<div class="panel-body">
@Html.HiddenFor(mbox => Model[i].ID)
<div class="form-group">
@Html.LabelFor(m => Model[i].Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => Model[i].Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => Model[i].Name, "", new { @class = "text-danger" })
// warning: abbreviated, originally 5 inputs in this panel-body
</div>
</div>
</div>
<div class="panel-footer">
<button type="button" id="ButtonDeleteIdea" class="btn btn-danger" value="@Model[i].ID">@CreateRes.DeleteIdea</button>
</div>
</div>
}
</div>
<div class="panel-footer">
<button type="button" class="btn btn-primary ButtonAddIdea">@CreateRes.AddIdea</button>
</div>
使用的Ajax调用:
$(function () {
$(".ButtonAddIdea").click(function () {
var data = testFct();
alert(data);
$.ajax(
{
type: "POST",
url: window.AddAnotherIdea,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: data,
}).done(function (html) {
$("#IdeaList").replaceWith(html);
});
});
});
function testFct() {
var list = $("#IdeaList :input")
var test = list.serializeArray()
things = JSON.stringify({ 'ideas': test });
return things
}
接收方法:
[HttpPost]
public async Task<PartialViewResult> AddAnotherProjectIdea(List<ProjectIdea> ideas)
{
// gets called, and the List is not null - but the list appears to contain only
// gibberish, with every value 0 or NULL.
//Also there are 5 elements, there should be only one
}