I am attempting to pass back an object with a property that is a collection of objects but when using the serialized form as the data attribute in my Ajax post the collection is empty (null). Is this the wrong way to pass back a object that contains a list as a property or is there something simple I am over-looking? When I step into the controller action I can see that I have the Holder.Id attribute populated but MyList is empty.
I have tried making the contentType: ‘application/json’ with no help. I would like to have the full object as the payload for Ajax post instead of each individual item in the collection. When calling Ajax with each individual item it does work and I may have to use that method.
Simple POCO objects:
public class Holder
{
public int Id { get; set; }
public List<Contained> MyList { get; set; }
}
public class Contained
{
public int Id { get; set; }
public string Name { get; set; }
}
Controller methods:
[HttpGet]
public ActionResult Edit()
{
List<Contained> contained = new List<Contained>();
contained.Add(new Contained{Id=123, Name="123Name"});
contained.Add(new Contained{Id=456, Name="456Name"});
return View(new Holder { Id = 1001, MyList = contained });
}
[HttpPost]
public JsonResult Edit(Holder holder)
{
return Json("Succeeded");
}
Html Markup:
@model Compeat.MyMvcApp.Controllers.Holder
@{
ViewBag.Title = "Edit";
}
<script type="text/javascript">
$(document).ready(function () {
$("#btnAdd").click(function () {
var coll = [];
var newName = $("#txtAddNameToList").val();
coll.push(newContainedJson(999, newName));
$("#MyList").val(coll);
var frmElems = $("form").serialize();
console.log(coll);
$.ajax({
type: "POST",
data: coll,
url: "Edit",
dataType: "json",
success: function (data) { alert('worked!'); },
error: function (data) {
alert('error: ' + data.responseText);
}
});
});
function newContainedJson(id, name) {
return { "Id": id , "Name": name };
}
});
</script>
<ul>
@foreach (var o in Model.MyList)
{
<li>@o.Name</li>
}
</ul>
@{ using (Html.BeginForm())
{
@Html.HiddenFor(e => e.Id)
<input type="hidden" name="MyList" id="MyList" value="" />
<input type="text" id="txtAddNameToList" name="txtAddNameToList" />
<input type="button" id="btnAdd" value="Add Name" />
}}
Use the JQuery below and set a breakpoint in your controller.