0

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.

Shawn Mclean
  • 56,733
  • 95
  • 279
  • 406

2 Answers2

1

Not exactly sure what you're trying to do, but if you want to display a list of phone numbers in your view, you do this:

<ul id="PhoneList">
@foreach (var p in Model.Phones) {
    <li>@p.Number</li>
}
</ul>

What are you trying to achieve with your jquery function?

mnsr
  • 12,337
  • 4
  • 53
  • 79
0

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:

<input type="texbox" name="Phones[0].Number" />
<input type="texbox" name="Phones[1].Number" />
<input type="texbox" name="Phones[2].Number" />

So you need to mimic that. Something like this:

$('#AddBtnPhone').click(function(){
    var $phoneList = $('#PhoneList');
    var numberOfExistingElements = $phoneList.children('.phone').length;
    $phoneList.append('input')
       .attr('type','textbox')
       .attr('name', 'Phones[' + numberOfExistingElements+1 + '].Number')
       .addClass('phone');    
});

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.

RPM1984
  • 72,246
  • 58
  • 225
  • 350
  • What if I want to remove the second index? Would I have to loop through and re-index the others? Because if I have [0] and a [2], nothing gets binded to the controller action – Shawn Mclean Nov 30 '11 at 19:40
  • @Lol - yes, you should rebind/reindex your array. Check out this: http://stackoverflow.com/questions/5237387/algorithm-to-re-index-an-array-of-objects-after-insertion-or-drag-n-drop-order – RPM1984 Nov 30 '11 at 22:58