views:

43

answers:

3

Hi, 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.push(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 :)

+1  A: 

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
} 
Byron Sommardahl
A: 

Byron! I salute your Ninjaness. Thanks that worked!

Do you know how I could deserialise this Server/C# side into something nice?

Garth
Can you mark my answer with your approval? Also, if you wouldn't mind, move your question to the comments below my answer and delete this post. In the mean time, I'll see if I can come up with an answer to that question. This site works a little different from a forum in that there should be one question at the top of the page and possible answers below. If someone gets the answer right or answers it the best way, you mark it as the answer. When you get some more reputation points, you'll be able to upvote answers/questions, which is another very nice thing to do for ninjas like myself. :)
Byron Sommardahl
A: 

Brad. How do I mark your post as an answer? I dont have enough points to vote for it.

Regards