Form using Begincollectionitem gets null viewModel in foreach

Asked

Viewed 957 times

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 only pessoaViewModel

or

  • call no viewModel why when I do the Html.renderPartial, I wouldn’t be passing the model for 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 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.

1 answer

4


The code is perfect. That’s what it is to do. Now you mount the Viewmodel so that all this code makes sense. That is to say:

// 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 keep the pattern. If you used "Phones" here:

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

The property also needs to call Telefones in Viewmodel:

public class PessoaViewModel
{
    ...
    public virtual ICollection<PessoaTelefoneViewModel> Telefones { get; set; }
}
  • And what model do I use in the partial view of phones? if I use direct phone and not person phone, it is not received in controller, and if I use person phone, I can’t access phone properties...

  • In the Partial you use @model SeuProjeto.ViewModels.PessoaTelefoneViewModel>. Try filling a phone and make one Debug in Action Create who receives the POST. You have to show up there yes.

  • It appears, but as null, so if I put that the controller tbm receives phoneViewModel the values are received, I could leave working like this, but then as it would receive several phoneViewModels?

  • As well as receiving several PessoaTelefoneViewModel? It’s wrong. You have to receive only PessoaViewModel and the phones are inside PessoaViewModel as a list, as you yourself put in the question.

  • Yes I understood that, I expressed it wrong, that’s what I meant, she’ll get a list... but she’s getting null

  • This is already weird. You have to host this project in some version control and pass the link, like a Github?

  • 1

    I managed to solve, had a different letter in the name of Collection and the property, now it worked beauty, and now the button to add?

  • @So I’d better ask you another question. Go into Ajax and stuff.

  • http://answall.com/questions/80887/fazer-um-bot%C3%A3o-to-add-properties-in-a-list-using-o-begincollectionit

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.