Posting Javascript objects with jQuery to MVC ActionResult
I have created a client side array of javascript objects that I'd like to post back to the server. But when I do the following the array is coming back as 'undefined' Serverside in the FormCollection.
I'm using jQuery and here is my javascript code:
function MyObject(){
this.Param1;
this.Param2;
}
var myArray = new Array();
var newObject1 = new MyObject();
newObject1.Param1 = "abc";
newObject1.Param2 = "efg";
myArray.push(newObject1);
var myArray = new Array();
var newObject2 = new MyObject();
newObject2.Param1 = "hij";
newObject2.Param2 = "klm";
myArray.p开发者_JAVA技巧ush(newObject2);
$.post("Save", myArray, function (result) { PostDataCallBack(result); });
Does anyone have an example of something like this or any ideas on how to serialize javascript objects and post them?
Thanks :)
The items in your array have to have the same name when posted to your actionMethod. As long as they have the same name, the modelBinder will likely pick them up and stuff them into your actionMethod's array param. Right now, it looks like you're not defining a name for your array. That might mean it's using a default name, but your actionMethod's param name must match.
Try this:
$.post(
"Save",
{ myArray: myArray },
function (result) { PostDataCallBack(result); }
);
Try having a c# class that matches your javascript object so the modelBinder can really do something nice for you:
public class MyObject
{
public string Param1 { get; set; }
public string Param2 { get; set; }
}
Then, your action method should look like this:
public ActionResult Save(MyObject[] MyArray) {
//DO STUFF HERE
}
精彩评论