Reputation: 7416
I'm new with JSON and I try to pass some data in a JsonResult method located in my controller. The method accepts an AModel as a parameter. This AModel is defined with some properties, and a BModel.
So, I wrote :
function loadDatas() {
var values =
{
"Title" : "The title",
"Text" : "Blahblahblah",
"BModel" :
{
"Summary" : "lorem ipsum",
"Page" : "15"
}
};
$.post("@Url.Action("Load", "MyController")",values,function(data)
{
// do stuff;
});
And my Load method is defined as :
[HttpPost]
public JsonResult Load(AModel test)
{
return Json(test); //dummy example, just serialize back the AModel object
}
When I put a breakpoint on Load's opening brace, test.Title and test.Text have the good values, but test.BModel.Summary and test.BModel.Page are null.
The worst part in this problem is if I put an alert(values.HousingModel.Summary); the value displayed is the good one ! Why is it not send correctly to my method whereas values.Title and values.Text are ??
I used this link to understand JSON format (http://www.sitepoint.com/javascript-json-serialization/) and mine seems valid... Isn't it ?
Thanks for your help
Alex
Upvotes: 2
Views: 1733
Reputation: 6728
Action Method
[HttpPost]
public JsonResult Json(AModel test)
{
return Json(new { Success = true });
}
JQuery
$.ajax({
url : "@Url.Action("Load", "MyController")",
contentType : "application/json; charset=utf-8",
dataType : "json",
type : "POST",
data : JSON.stringify({test: values})
})}).done(function (result) {
//Success
}).fail(function (result) {
//Failed
}).always(function(result) {
//Always
});
Models
public class AModel
{
public string Title { get; set; }
public string Text { get; set; }
public BModel BModel { get; set; }
}
public class BModel
{
public string Summary { get; set; }
public string Page { get; set; }
}
Mistakes
Upvotes: 1
Reputation: 5443
Without seeing hour Model we can't give you definitive answer but... is it possible that your BModel.Page is an integer in C#? If so the Model binder can't set your values on that SubObject with your javascript string value...
Upvotes: 0