Lets say I have some view models set up as follows:
public class User
{
public string Name {get; set;}
public IList<Phone> Phones {get; set;}
}
public class Phone
{
public string Number {get; set;}
}
My view is setup as follows:
@(form){
<div>
@Html.EditorFor(model => model.Name)
<!-- Should be dynamic creation of phone numbers -->
<a id="AddBtnPhone">add</a>
<ul id="PhoneList">
</ul>
<input type="submit"/>
</div>
}
<script>
$(function(){
$('#AddBtnPhone').click(function(){
//What do I do here?
});
});
</script>
How do I add phone numbers dynamically so when this form gets posted, they are all in the list collection? I have no idea how to setup my views.
Scenario:
When the use clicks add, a list item containing a textbox to accept a phone number is added to PhoneList. When submit is clicked, the model User is posted to the controller with 1 element in the Phones list that contains the entered phone number.
When you dynamically create the input elements, you need to mimic the way MVC names the form elements so the model binding kicks in.
For example, if you had a list of 3 phone numbers and let MVC render them out, they would look like this:
So you need to mimic that. Something like this:
I made this up off the top of my head (untested), so it may not be 100% (such as zero-based indexing for the array) but you get the idea.