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 receivingpessoaViewModel
or
- do not call any viewModel because when I do
Html.renderPartial
, I would not be passing the model toforeach
?
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?