jquery - MVC 3 - Render additional Editor templates for children objects -


i'm trying create form allows user create an entity 0-multiple children objects, main object being lead has 0-many beneficiary , payer objects. relation between 3 follows:

lead has many beneficiaries (one many) lead has many payers (many many) joined through leadspayers 

in editor lead view model have loop generates editor each beneficiary , payer attached lead want able have button dynamically add beneficiary or payer lead , use editor template don't have duplicated html in javascript code.

i have working bind lead when form gets posted controller don't know how reuse editor template code generate compatible html current form, has done before? there has better way ajax button renders html

this helped me on right track wasn't wanted , doesn't seem supported in mvc here work around work model binding in controller.

my end goal

to dynamically add children objects form proper html auto bound parent when passed control method, meaning needed html this

<input name='lead_beneficiaries_1__{property}' id=... /> 

and not (which blog post results in)

<input name='beneficiary__{property}' /> 

which doesn't auto bind parent when posted controller.

solution

instead of using ajax render editor template html controller, auto render 1 editor template when form loaded , more can loaded needed user. jquery code

$("#addbeneficiary").click(function(e) {     e.preventdefault();     var beneficiary = $(".beneficiary:last").clone();     var count = parseint(beneficiary.find("input:first").attr("id").match(/\d+/), 10);     beneficiary.find("input").each(function(indx, element) {          var name = $(element).attr('name').replace(count, count+1),             id   = $(element).attr('id').replace(count, count+1);         $(element).attr('name', name);         $(element).attr('id', id);         $(element).val('');      });     $("#beneficiaries").append(beneficiary); }); 

i wrapped editor template in div can grabbed whole jquery, cloned it, emptied values of inputs , incremented counter each element when posted collection of children entities on parent without having explicitly catch them in method or pull them formcollection dictionary.

while isn't best solution, gets job done in way intended , didn't end duplicating html editor template. if form errors since parent object has multiple children auto rendered automatically form code , nothing lost because of client side additions.


Comments

Popular posts from this blog

Javascript line number mapping -

c# - Is it possible to remove an existing registration from Autofac container builder? -

php - Mysql PK and FK char(36) vs int(10) -