I have a set of list elements, that I create dynamically. Each of these list elements, contains an input text, whose value I want to pass to the controller.
<ul id="list"></ul>
<button id="add">Add</button>
<script>
var counter = 1;
$('#add').click(function () {
var text = '<input type="text" name="(what should I put here?)"></input>';
var li = '<li>' + text + '</li>';
$(li).appendTo('#list');
counter++;
return false;
});
</script>
public IEnumerable<string> list {get; set;}
...
How can I bind those values to my ViewModel implicitly? I have tried to use the counter
variable to assign a name to each created element (like list[counter]
), but on the controller side the list
variable on my ViewModel still comes empty.
First I would base your counter on the amount of li's within your un-ordered list with:
$('#list > li').size()
Then in order to keep the model binder happy pre-fix your property with list:
'<input type="text" name="list[' + counter + ']"></input>'
The full code then becomes:
$('#add').click(function () {
var counter = $('#list > li').size();
var text = '<input type="text" name="list[' + counter + ']"></input>';
var li = '<li>' + text + '</li>';
$(li).appendTo('#list');
return false;
});
jsFiddle
Please note, you will have to change your view model property to an IList
or List
for indexing to work too:
public IList <string> list {get; set;}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With