Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I'm not sure what do you mean 'collection variable names' and probably my solution is kind of magic you noticed.</p> <p>My solution is based on copying existing editor for element and altering input names via Javascript.</p> <p>First of all, we need to mark up our editor. This is a code of form outputs editor for collection</p> <pre><code> @for (var i = 0; i &lt; Model.Count; i++) { &lt;div class="contact-card"&gt; @Html.LabelFor(c =&gt; Model[i].FirstName, "First Name") @Html.TextBoxFor(c =&gt; Model[i].FirstName) &lt;br /&gt; @Html.LabelFor(c =&gt; Model[i].LastName, "Last Name") @Html.TextBoxFor(c =&gt; Model[i].LastName) &lt;br /&gt; @Html.LabelFor(c =&gt; Model[i].Email, "Email") @Html.TextBoxFor(c =&gt; Model[i].Email) &lt;br /&gt; @Html.LabelFor(c =&gt; Model[i].Phone, "Phone") @Html.TextBoxFor(c =&gt; Model[i].Phone) &lt;hr /&gt; &lt;/div&gt; } </code></pre> <p>Our editor is placed into div with class <code>contact-card</code>. On rendering, ASP.NET MVC gives names like <code>[0].FirstName</code>, <code>[0].LastName</code> ... <code>[22].FirstName</code>, <code>[22].LastName</code> to inputs used as property editors. On submitting Model Binder converts this to collection of entities based both on indexes and property names.</p> <p>Next we create javascript function that copies last editor and increases index in brackets by 1. On submitting it adds additional element to collection: </p> <pre><code>var lastContent = $("#contact-form .contact-card").last().clone(); $("#contact-form .contact-card").last().after(lastContent); $("#contact-form .contact-card") .last() .find("input") .each(function () { var currentName = $(this).attr("name"); var regex = /\[([0-9])\]/; var newName = currentName.replace(regex, '[' + (parseInt(currentName.match(regex)[1]) + 1) + ']'); $(this).val(''); $(this).attr('name', newName); }); </code></pre> <p>VOILA!! On submitting we will get one more element!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload