0

I need way to display a "List" property with the option to add new elements to the list.

So Basically

  • Value 1
  • Value 2
  • Button: Add new

I created an editfor template for it, where I display all the values with a foreach loop. However, each item get's an index, so when I add a new input field with javascript, the index is wrong.

Any suggestions how to achieve this.

PS: the adding of new elemens mustbe done on the client, since it is a simple form

Stefan
  • 14,826
  • 17
  • 80
  • 143
  • Can you show your loop code? If you are using a `foreach`, this won't work. – AJ. Jan 23 '15 at 12:55
  • yeah; I'm using a for loop. I got that foreach doesn't work because it adds the name you defined in the foreach statement to the form. However I still need a way to add the index... – Stefan Jan 23 '15 at 12:57
  • When you render your view, save the `Count` to a JavaScript variable. You'll know then what the next available index is. – Andrei V Jan 23 '15 at 13:03
  • isn't there some standard widget which might do this for me? – Stefan Jan 23 '15 at 13:04
  • None that I'm aware of... – Andrei V Jan 23 '15 at 14:07
  • See my answer on this question. It might help you. http://stackoverflow.com/questions/25286797/how-to-handle-repeating-form-fields-in-asp-mvc/25287349#25287349 – jamesSampica Jan 23 '15 at 16:23
  • [Refer this answer](http://stackoverflow.com/questions/28019793/submit-same-partial-view-called-multiple-times-data-to-controller/28081308#28081308) for some further example of how to dynamically add objects to a collection –  Jan 23 '15 at 23:47

1 Answers1

0
    var abccounter = 1;

    $("#abcbutton").click(function () {

        $('#itemlist').append('<p><input class="text-box single-line" id="listofstringname_' + abccounter + '_" name="listofstringname[' + abccounter + ']" type="text" value=""></p>');

        abccounter++;
    });


<p>@Html.EditorFor(model => model.listofstringname)</p>

that is what I did and it worked. the only problem I'm having (and it may be solved eventually) is I want to wrap each element with a

tag but I'm not sure how. this JS just adds a new "text box element" assuming 1 as the start as my model loads 1 example by default.

Bryce
  • 664
  • 6
  • 17