2
I want to make a form where I can register several addresses and phones to a single person, and I want to be able to do this when I’m registering the person.
Based on the answers to my other question, I got to the part where I put the telefoneViewModel
inside pessoaViewModel
as a IList
, then I make a foreach
in my view, who calls the partial view phone. I have a if
whether the viewModel is void before doing the foreach
, but there mine viewModel is always coming null, and does not render the partial view telephone.
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 calling properties:model.pessoaTelefoneViewModel.propriedade
or
pessoaTelefoneViewModel
directly, but I believe that after the controller do not receive her, because there I am receiving onlypessoaViewModel
or
- call no viewModel why when I do the
Html.renderPartial
, I wouldn’t be passing the model forforeach
?
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 a mistake of System.NullReferenceException
. How do I fix it?
Before calling the view the Viewmodels list is null? Maybe you have to create this list before sending it to the screen.
– Thiago Silva