I am passing back Json via a jQuery AJAX call to a MVC function that takes a Folder. MVC correctly parses some of the data but not the list I sent back.
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, in this function gets set with Id and Name but SearchCriteria is not set properly. It is set to null. If I comment out the traditional: true the list gets created but all the values for each SearchCriteria are 0 or null.
Am I missing something?
Imad Alazani
6,7287 gold badges38 silver badges58 bronze badges
asked Aug 20, 2013 at 8:44
Chris
27.5k49 gold badges208 silver badges358 bronze badges
1 Answer 1
You are missing two points
1. contentType: 'application/json; charset=utf-8',
2. data: JSON.stringify(folder)
And one correction.
URL should be like
url : "@Url.Action("ActionName", "ControllerName", new { area = "AreaName" })"
jQuery
$.ajax({
url: "@Url.Action("Action", "Controller", new { area = "Area" })",
type: "POST",
contentType: 'application/json; charset=utf-8',
dataType: "json",
data: JSON.stringify(folder),
traditional: true,
success: function (data) {
alert("wsaved");
}
});
answered Aug 20, 2013 at 8:55
Imad Alazani
6,7287 gold badges38 silver badges58 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Explore related questions
See similar questions with these tags.
lang-cs
data:option, and jQuery will convert the object to a query string, likeId=foo&Name=bar&.... If you really want to send JSON, you have to convert the object to JSON, likedata: JSON.stringify(JSON). Whether that is the problem or not, I cannot say (I don't know MVC).contentType: 'application/json; charset=utf-8',2.data: JSON.stringify(folder),And one correction. URL should be likeurl : "@Url.Action("ActionName", "ControllerName", new { area = "AreaName" })"SearchCriteria=Arrayinstead of the actual array. I didn't make binding of list by the past, but you can check this out : hanselman.com/blog/…