0

我有一个对象 MainObject,其中包含对象列表、子对象等。我试图让用户单击视图上的链接以向页面添加新的子对象。但是,我无法将正在使用的 MainObject 传递给 Action 方法。我目前收到的 MainObject 是空的,它的所有值都设置为 null。如何将最初用于渲染视图的 MainObject 发送给我的控制器操作?

视图的相关部分如下所示:

    <div class="editor-list" id="subObjectsList">
        <%: Html.EditorFor(model => model.SubObjects, "~/Views/MainObject/EditorTemplates/SubObjectsList.ascx")%>
    </div>
     <%: Ajax.ActionLink("Add Ajax subObject", "AddBlanksubObjectToSubObjectsList", new AjaxOptions { UpdateTargetId = "subObjectsList", InsertionMode = InsertionMode.Replace })%>

控制器的相关功能如下所示:

    public ActionResult AddBlanksubObjectToSubObjectsList(MainObject mainobject)
    {
        mainobject.SubObjects.Add(new SubObject());
        return PartialView("~/Views/MainObject/EditorTemplates/SubObjectsList.acsx", mainobject.SubObjects);
    }
4

1 回答 1

0

我最终得到以下结果:

看法:

        <div class="editor-list" id="subObjectsList">
            <%: Html.EditorFor(model => model.SubObjects, "~/Views/MainObject/EditorTemplates/SubObjectsList.ascx")%>
        </div>
        <input type="button" name="addSubObject" value="Add New SubObject" onclick="AddNewSubObject('#SubObjectList')" />

控制:

 public ActionResult GetNewSubObject()
    {
        SubObject subObject= new SubObject();
        return PartialView("~/Views/TestCase/EditorTemplates/SubObject.ascx", subObject);
    }

最后,我添加了这个 JQuery 脚本:

   function AddNewSubObject(subObjectListDiv) {
        $.get("/TestCase/GetNewSubObject", function (data) {

            //there is one fieldset per SubObject already in the list,
            //so this is the index of the new SubObject
            var index = $(subObjectListDiv + " > fieldset").size();

            //the returned SubObject prefixes its field namess with "[0]."
            //but MVC expects a prefix like "SubObjects[0]" - 
            //plus the index might not be 0, so need to fix that, too
            data = data.replace(/name="\[0\]/g, 'name="SubObject[' + index + "]");

            //now append the new SubObject to the list
            $(subObjectListDiv).append(data);
        });
    }

如果有人有比使用 JQuery 将嵌套对象的 MVC 语法合并到返回的视图更好的方法,请发布它;我很乐意相信有更好的方法来做到这一点。现在,我接受我的回答。

于 2011-03-03T00:22:08.033 回答