1
我通過jQuery AJAX調用將Json傳回給需要Folder
的MVC函數。 MVC正確解析了一些數據,但不是我發回的列表。Json沒有正確解析MVC4中的jQuery AJAX調用
MVC
public class Folder : IValidate
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<SearchCriteria> SearchCriteria { get; set; }
}
public class SearchCriteria
{
public int FolderId { get; set; }
public int SettingsEntryID { get; set; }
public string SearchParameter { get; set; }
}
public ActionResult EditFolder(Folder folder)
{
service.EditFolder(folder);
return this.Json(Json(new { Success = true }));
}
的Javascript
var folder = {
Id: $("#groupID").val(),
Name: $("#groupName").val(),
SearchCriteria: []
};
$(".searchCriteria").each(function() {
folder.SearchCriteria.push(
{
FolderId: $("#groupID").val(),
SearchParameter: $(this).val(),
SettingsEntryID: $(this).attr("id").replace("searchCriteria", "")
});
});
$.ajax({
url: "/settings/editfolder/",
type: "POST",
dataType: "json",
data: folder,
traditional: true,
success: function (data) {
alert("wsaved");
}
});
folder
,在此功能被設定Id
和Name
但SearchCriteria
設置不正確。它設置爲null
。如果我註釋掉traditional: true
,則會創建列表,但每個SearchCriteria
的所有值都是0
或null
。
我錯過了什麼嗎?
您是*不*發送JSON。您將對象作爲'data:'選項傳遞,jQuery將把對象轉換爲查詢字符串,如'Id = foo&Name = bar&...'。如果您真的想發送JSON,則必須將該對象轉換爲JSON,如'data:JSON.stringify(JSON)'。不管這是不是問題,我不能說(我不知道MVC)。 –
你缺少兩點1.'contentType:'application/json; charset = utf-8','2。'data:JSON.stringify(folder),'**和一個更正。** URL應該像'url:「@ Url.Action(」ActionName「,」ControllerName「,新的{area =「AreaName」})「' –
當你發送你的文章時,Ajax實際上會發送類似'SearchCriteria = Array'的東西而不是實際的數組。以前我沒有列出綁定列表,但您可以查看以下內容:http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx –