Form using BeginCollectionItem gets null viewModel in foreach

2

I want to make a form where I can register multiple addresses and phones for a single person, and I want to be able to do this when I am registering the person.

Based on the answers to my other question , I came to the part where I put telefoneViewModel inside pessoaViewModel as a IList , so I foreach in my view , which calls the partial view phone. I have if that checks if the viewModel is null before doing foreach , but then my viewModel is always null, partial view .

My controller :

 // GET: Pessoas/Create
    public ActionResult Create()
    {
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(PessoaViewModel pessoaViewModel)
     {       
           // salvando os dados     

            return RedirectToAction("Index");
    }

My main 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>

//resto da view...

In my partial view I have doubts which model to call:

  • pessoaViewModel and then access the properties by calling: model.pessoaTelefoneViewModel.propriedade

or

  • pessoaTelefoneViewModel directly, but I believe that the controller will not receive it, since I'm only receiving pessoaViewModel

or

  • do not call any viewModel because when I do Html.renderPartial , I would not be passing the model to foreach ?

Partial view :

@using (Html.BeginCollectionItem("Telefones"))
{
     <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...
}

If I leave without the if, it gives an error of System.NullReferenceException . How do I resolve this?

    
asked by anonymous 13.08.2015 / 19:41

1 answer

4

The code is perfect. That's what it's supposed to do. Now you mount the ViewModel so that all this code makes sense. That is:

// GET: Pessoas/Create
public ActionResult Create()
{
    var pessoaViewModel = new PessoaViewModel {
        // Aqui você poderia preencher os dados da pessoa. 
        // Minha dica é inserir uma lista com um elemento vazio em telefone.
        Telefones = new List<PessoaTelefoneViewModel> 
        {
            new PessoaTelefoneViewModel()
        }
    };

    return View(pessoaViewModel);
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(PessoaViewModel pessoaViewModel)
 {       
       // salvando os dados     

        return RedirectToAction("Index");
}

Another thing: try to stick to the pattern. If you used "Phones" here:

@using (Html.BeginCollectionItem("Telefones"))

The property must also call Telefones in ViewModel :

public class PessoaViewModel
{
    ...
    public virtual ICollection<PessoaTelefoneViewModel> Telefones { get; set; }
}
    
13.08.2015 / 20:58