i'm trying to post an array of objects to an action within a controller. If I post using a regular submit button everything works as expected, however when i try posting via Ajax, the list is always empty. Any ideas? My code is below.
View:
@using (Html.BeginForm("Save", "Home", FormMethod.Post, new { id = "myform" }))
{
<input type="text" name="Childs[0].Name" value="Name 1" />
<input type="text" name="Childs[0].Age" value="12" />
<input type="text" name="Childs.Index" value="0" />
<input type="text" name="Childs[1].Name" value="Name 2" />
<input type="text" name="Childs[1].Age" value="23" />
<input type="text" name="Childs.Index" value="1" />
<input type="text" name="AnotherProperty" value="111" />
<input type="button" onclick="PostForm()" value="Test" />
}
Model:
public class BinderTestModel
{
public BinderTestModel()
{
Childs = new List<BinderTestChildModel>();
}
public int AnotherProperty { get; set; }
public List<BinderTestChildModel> Childs { get; set; }
}
public class BinderTestChildModel
{
public string Name { get; set; }
public int Age { get; set; }
}
JS:
function PostForm()
{
$.ajax({
url: '@Url.Action("Save")',
type: "POST",
contentType: 'application/json; charset=utf-8',
datatype:'json',
data: JSON.stringify($("#myform").serialize()),
success: function()
{
},
error: function (jqXHR, exception) {
alert('Error message.');
}
});
}
Thanks,
Gonzalo