I have run into an issue attempting to pass an array of objects to an MVC3 controller/action. I've found several discussions on the web (including here at SO) but none have solved my problem. Here is what I'm working with:
public class Person
{
public Guid TempId { get; set; }
public bool ReadOnly { get; set; }
[Required(ErrorMessage = "Required")]
public string Name { get; set; }
}
Here is what my controller action (currently, I've tried many variations) looks like:
[HttpGet]
public ActionResult AddPerson(List<Person> people)
{
if (null != people)
{
foreach (var person in people)
{
Debug.WriteLine(person );
}
}
return View();
}
I have tried numerous ways of structuring my jquery in order to call to action, but so far the only one I can get to work is if I manually encode the array of objects into the URL string like so:
var url = "AddPerson?people%5B0%5D.TempId=9FBC6EF8-67DB-4AB4-8FCE-5DFC0F2A69F9&people%5B0%5D.ReadOnly=true&people%5B0%5D.Name=Bob+Jones&people%5B1%5D.TempId=9FBC6EF8-67DB-4AB4-8FCE-5DFC0F2A6333&people%5B1%5D.ReadOnly=false&people%5B1%5D.Name=Mary+Jones #peopleDiv";
$("#peopleDiv").load(url, updatePeopleDiv);
The people%5B1%5D.ReadOnly=false
is the encoded version of people[1].ReadOnly=false
I've tried other things such as:
var url = "AddPerson #peopleDiv";
var people = [];
people.push({'[0].TempId': '<valid guid>', '[0].ReadOnly': true, '[0].Name': 'Bob Jones' });
$("#peopleDiv").load(url, people, updatePeopleDiv); // nope
$("#peopleDiv").load(url, $.param(people, false), updatePeopleDiv); // nada
$("#peopleDiv").load(url, $.param(people, true), updatePeopleDiv); // nyet
I have also tried modifying the above by wrapping that people[] inside an object: var data = { arr: people }
and then trying to send that data
object various ways. All the ways (other than the one I got to work by manually encoding) result in one of three outcomes:
- No controller action called (mismatch between how it's defined and how I called it)
- Controller action called but param is null
- Controller action called, and correct number of object elements in the array BUT none of the actual values from those objects is transferred (so I have an array of objects all with default values).
Any suggestions?