3
I have a register of people and need to create a button to add multiple phones and send to my controller, I am using Begincollectionitem, based on my other question Form using Begincollectionitem gets null viewModel in foreach just missing part of the button, as I do?
My controller:
    // GET: Pessoas/Create
    public ActionResult Create()
    {
        var pessoaViewModel = new PessoaViewModel
        {
            PessoaTelefoneViewModel = new List<PessoaTelefoneViewModel> 
            {
                new PessoaTelefoneViewModel()
            }
        };
        return View(pessoaViewModel);
    }
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(PessoaViewModel pessoaViewModel)
     {
            //salvando os dados         
            return RedirectToAction("Index");
    }
My view:
@model meuprojeto.ViewModels.PessoaViewModel
// resto da view...
<div id="tab-3" class="tab-pane">
     @if (Model != null && Model.PessoaTelefoneViewModel != null)
     {
         foreach (var telefone in Model.PessoaTelefoneViewModel)
         {
            Html.RenderPartial("_Telefone",telefone);
         }
      }
 </div>
My partial phone view:
@model meuprojeto.ViewModels.PessoaTelefoneViewModel
@using (Html.BeginCollectionItem("PessoaTelefoneViewModel"))
 {
     <div class="form-group">
        @Html.LabelFor(model => model.Descricao, new {@class = "col-md-12   "})
        <div class="col-md-10">
            @Html.EditorFor(model => model.Descricao, new {htmlAttributes = new {@class = "form-control "}})
            @Html.ValidationMessageFor(model => model.Descricao, "", new {@class = "text-danger"})
        </div>
    </div>
   //outros campos...
}
						
It worked perfectly! thank you very much, it helped me a lot!!
– Aesir
When I send the form and the modelState is not valid, it returns to the same create view, so what I typed on phone, is lost... there is some way to recover what I typed before?
– Aesir
@Aesir Yes, forward the Viewmodel for View shortly after the
if (ModelState.IsValid) { ... }. Thus:return View(viewModel);.– Leonel Sanches da Silva
Gosh, since I didn’t try it, thank you again.
– Aesir