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


i have object mainobject list of objects, subobjects, among other things. trying have user click link on view add new subobject page. however, unable pass mainobject working action method. mainobject receive empty, values set null. how send controller action mainobject used render view originally?

the relevant section of view looks 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 controller looks this:

    public actionresult addblanksubobjecttosubobjectslist(mainobject mainobject)     {         mainobject.subobjects.add(new subobject());         return partialview("~/views/mainobject/editortemplates/subobjectslist.acsx", mainobject.subobjects);     } 

i ended 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, added jquery script:

   function addnewsubobject(subobjectlistdiv) {         $.get("/testcase/getnewsubobject", function (data) {              //there 1 fieldset per subobject in list,             //so index of new subobject             var index = $(subobjectlistdiv + " > fieldset").size();              //the returned subobject prefixes field namess "[0]."             //but mvc expects prefix "subobjects[0]" -              //plus index might not 0, need fix that,             data = data.replace(/name="\[0\]/g, 'name="subobject[' + index + "]");              //now append new subobject list             $(subobjectlistdiv).append(data);         });     } 

if has better way kludging mvc syntax nested objects onto returned view using jquery, please post it; i'd love believe there better way this. now, i'm accepting answer.


Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -