Make a button to add properties to a list using Begincollectionitem C#

Asked

Viewed 2,091 times

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...
}

1 answer

3


Alter the View main to the following:

@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>
     <p><a id="add-another" class="small-button">Adicionar Telefone</a></p>

@section Scripts {
    <script type="text/javascript">
        $("#add-another").click(function () {
            $.get('/Pessoas/LinhaTelefone', function (template) {
                $("#tab-3").append(template);
            });
        });
    </script>
}

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");
}

public ActionResult LinhaTelefone()
{
    var telefone = new PessoaTelefoneViewModel();
    return PartialView("_MinhaPartial", telefone);
}

Functioning

  • By clicking "Add Phone", the Controller will be triggered to format the piece of View which will be incorporated into the code;
  • The Controller, in turn, it will return a partial to the calling Ajax;
  • Once this is done, Javascript changes the <form> with the new piece coming from Controller.
  • 1

    It worked perfectly! thank you very much, it helped me a lot!!

  • 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?

  • 1

    @Aesir Yes, forward the Viewmodel for View shortly after the if (ModelState.IsValid) { ... }. Thus: return View(viewModel);.

  • Gosh, since I didn’t try it, thank you again.

Browser other questions tagged

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