ASP .NET MVC 2 - How do I pass an object from View to Controller w/ Ajax?

540 Views Asked by At

I have an object MainObject with a list of objects, SubObjects, among other things. I am trying to have the user click a link on the View to add a new SubObject to the page. However, I am unable to pass the MainObject I am working with into the Action method. The MainObject I currently receive is empty, with all its values set to null. How do I send my controller action the MainObject that was used to render the View originally?

The relevant section of the view looks like this:

    <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 })%>

The relevant function from the controller looks like this:

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

There are 1 best solutions below

0
On BEST ANSWER

I ended up with the following:

View:

        <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')" />

Control:

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

And, finally, I added this JQuery script:

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

If someone has a better way to do this than kludging the MVC syntax for nested objects onto a returned View using JQuery, please post it; I'd love to believe that there is a better way to do this. For now, I'm accepting my answer.