Posted models (via jQuery) come back with all properties set to default
I fetch most of my data as models from my MVC app and just operate on them on the client side. When I'm done with whatever the user is doing I just post back the model/array of models to the server.
In a specific scenario, I'm posting an array with two models in it back to the app. I can see all the values of the model in the HTTP...but when they're deserialized and passed to my controller they come out "empty" -- that is, all the properties are set to their default values, but the collection has two elements in it.
Any ideas what could be the cause of this? It sounds like MVC isn't able to deserialize the HTTP to strongly typed objects, but I can't see why as everything "looks" OK in the HTTP. Is there some process that I could be missing?
If it's important I have tried "receiving" data as formal parameters of t开发者_开发技巧ype IList and MyModel[]...doesn't seem to help.
Hard for me to come up with specific code, but here goes -- perhaps this will help
// Client side
var models = new Array();
for(var i in selectedModels) {
var item = selectedModels[i];
if(typeof(item) != 'function') {
models.push(item);
}
}
$.ajax({
type: "POST",
data: { myModels: models, name: "" },
dataType: "json",
url: "/json/my-controller/create-models",
success: function (data, successCode, httpRequest) {
// Do some stuff
}
})
// Server Side
[HttpPost, ActionName("create-models")]
public ActionResult DoSomething(MyModel[] myModels)
{
if(myModels == null || myModels.Length < 1)
{
throw new InvalidOperationException("You must provide at least one model to add to the collection.");
}
// Do someother stuff...
return Json(someNewModel);
}
See this blog post. You need to use the json2.js library to stringify the data prior to posting. The stringify method allows JavaScript data structures to be serialised for transfer over http. You then need a Json Model Binder to help reconstruct the object server side.
Your js code would look like this :
var models = new Array();
for(var i in selectedModels) {
var item = selectedModels[i];
if(typeof(item) != 'function') {
models.push(item);
}
}
var postdata = JSON.stringify(models);
$.ajax({
type: "POST",
data: postdata ,
dataType: "json",
url: "/json/my-controller/create-models",
success: function (data, successCode, httpRequest) {
// Do some stuff
}
})
精彩评论