I’m using ASP.NET MVC2 and jQuery to load and save objects. I’m using knockout.js’s object serilization/deserialization to safely maintain the object’s data structure when loading/saving data.
When I send back my object in its exact structure back to the server using the following JavaScript method, on the server side in ASP.NET, my GraduationClass object gets instantiated but it has none of the data.
I checked the post data in firebug, and all of the data is properly being sent back to the server in the request in the correct structure, yet the ASP.NET MVC internal pipeline is failing to deserialize the data back into the GraduationClass object. I tried this both with and without the contentType setting.
I’m wondering what I’m doing incorrectly.
// javascript save method
function save(graduationClass) {
$.ajax({
url: "/SiteManagement/saveGraduationClass",
type: "POST",
// data: ko.mapping.toJSON(graduationClass), // (solution 1)
data: graduationClass, // (solution 2)
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
});
}
// both solutions result in a blank object construction on the server side
// ASP.NET MVC2 AJAX method
[HttpPost]
public ActionResult saveGraduationClass(GraduationClass graduationClass) {
// graduationClass here has all default data rather than the data sent in the post
return Json(new { resultText = "success" }, JsonRequestBehavior.AllowGet);
}
I believe there are two possible problem.
First, I’m pretty sure when you specify that you are sending JSON in an Ajax request, jQuery will Serialize Javascript Objects passed in the data parameter. You are definitely creating an jQuery object with a property
jsonwith a value of a string (I believe, I’m not familar with knockout). The value being passed to MVC would then look like:Which is of sorts a double serialization.
The second problem is, the previous JSON does not match your
saveGraduationClassmethod parametergraduationClass.I think either of these solutions should work:
or
Update
If I have this class:
and I have this JSON:
then it will populate this method:
However, the following JSON will not work:
It will also not match:
The layout of the JSON needs to match exactly the layout of the class trying to be populated.