My solution requires you to install the Package NuGet BeginCollectionItem HtmlHelper .
Controller
Logic required for editing only in Entity Framework 5. No 6 does not have to.
For creating a person, this logic can be simplified.
using (var scope = new TransactionScope())
{
// Entradas Excluídas
if (pessoa.Telefones == null)
{
foreach (var telefoneExcluido = context.Telefones.Single(t => t.TelefoneId == phone.CustomerPhoneID);
context.Telefones.Remove(telefoneExcluido);
context.SaveChanges();
} else {
// Registros Antigos
foreach (var telefone in context.Telefones.AsNoTracking().Where(t => t.PessoaId == pessoa.PessoaId).ToList())
{
if (pessoa.Telefones.Any(t => t.TelefoneId == telefone.TelefoneId))
{
var telefoneExcluido = context.Telefones.Single(t => t.TelefoneId == telefone.TelefoneId);
context.Telefones.Remove(telefoneExcluido);
context.SaveChanges();
}
}
// Phones
if (pessoa.Telefones.Any())
{
foreach (var telefone in pessoa.Telefones)
{
if (telefone.PessoaId == 0)
{
telefone.Pessoa = pessoa;
context.Telefones.Add(telefone);
} else {
context.Entry(telefone).State = EntityState.Modified;
}
context.SaveChanges();
}
}
}
context.Entry(pessoa).State = EntityState.Modified;
context.SaveChanges();
scope.Complete();
}
View Main
<div class="form-group">
@Html.LabelFor(model => model.Telefones)
<div class="controls">
<ul id="PhonesEditor" style="list-style-type: none">
@if (Model.Teleones != null)
{
foreach (var telefone in Model.Telefones)
{
Html.RenderPartial("_CustomerPhonesEditor", telefone);
}
}
</ul>
</div>
<p><a id="addAnother" class="small-button">@Language.AddPhone</a></p>
</div>
<script type="text/javascript">
$("#addAnother").click(function () {
$.get('/Customers/CustomerPhoneRow', function (template) {
$("#PhonesEditor").append(template);
});
});
</script>
_CustomerPhonesEditor.cshtml
@model SeuProjeto.Models.Telefone
@using (Html.BeginCollectionItem("Telefones"))
{
@Html.HiddenFor(model => model.TelefoneId)
@Html.HiddenFor(model => model.PessoaId)
<div class="form-group">
@Language.Phone
<div class="controls">
@Html.EditorFor(model => model.Numero)
<script type='text/javascript'>
$('input[name$="Numero"]').mask("(99) 9999-9999?9");
$('input[name$="Numero"]').focusout(function () {
var phone, element;
element = $(this);
element.unmask();
phone = element.val().replace(/\D/g, '');
if (phone.length > 10) {
element.mask("(99) 99999-999?9");
} else {
element.mask("(99) 9999-9999?9");
}
}).trigger('focusout');
</script>
@Html.ValidationMessageFor(model => model.Telefone)
</div>
</div>
<div class="form-group">
<div class="controls">
<a onclick="$(this).parent().parent().parent().remove();" class="small-button" style="float: left;">@Language.Delete</a>
</div>
</div>
}
Additional Action in the Controller, to insert a Partial by Ajax
public ActionResult LinhaTelefone()
{
var telefone = new Telefone();
return PartialView("_CustomerPhonesEditor", telefone);
}