0

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 :)

2
  • Can you post your ActionResult code where you are getting 'undefined'? Commented Jul 14, 2010 at 17:47
  • One problem is you're defining var myArray = new Array(); twice, thereby dropping the first object you push into "myArray". Commented Jul 14, 2010 at 18:11

1 Answer 1

1

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
} 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.