0

我试图传回一个具有属性的对象,该属性是对象的集合,但是在我的 Ajax 帖子中使用序列化表单作为数据属性时,该集合为空(null)。这是将包含列表作为属性的对象传回的错误方法,还是我忽略了一些简单的东西?当我进入控制器操作时,我可以看到我填充了 Holder.Id 属性,但 MyList 为空。

我试过在没有帮助的情况下制作 contentType: 'application/json' 。我希望将完整对象作为 Ajax 发布的有效负载,而不是集合中的每个单独项目。当使用每个单独的项目调用 Ajax 时,它确实有效,我可能不得不使用该方法。

简单的 POCO 对象:

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; }
}

控制器方法:

    [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标记:

@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" />
}}
4

1 回答 1

1

使用下面的 JQuery 并在控制器中设置断点。

 $("#btnAdd").click(function () {



        var data = {}
        data.Id = 9;
        data.MyList = [];
        data.MyList.push({ 'Id': 99, 'Name': 'Dude' });
        data.MyList.push({ 'Id': 990, 'Name': 'Dude2' });

        $.ajax({
            type: "POST",
            data: JSON.stringify(data),
            url: "Home/Index",
            dataType: "json",
            contentType: 'application/json',
            success: function (data) { alert('worked!'); },
            error: function (data) {

            }
        });
    });
于 2012-05-22T17:36:00.420 回答