ASP .NET MVC 2 - 如何使用Ajax将对象从View传递到Controller?

时间:2011-02-17 22:19:03

标签: asp.net-mvc-2 ajax.net

我有一个对象MainObject,其中包含一个对象列表,SubObjects等。我试图让用户单击视图上的链接以向页面添加新的SubObject。但是,我无法将我正在使用的MainObject传递给Action方法。我当前收到的MainObject是空的,其所有值都设置为null。如何将控制器操作发送到最初用于渲染View的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);
    }

1 个答案:

答案 0 :(得分: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语法克隆到返回的View上,请发布它;我很想相信有更好的方法来做到这一点。现在,我接受了我的回答。