help for View to pass multiple lines to a Controller

Asked

Viewed 213 times

1

Guys, I have a simple model for studies. There are 3 tables, Person, Allergy and Personal Allergy. Since a person can have several allergies.

My role model is:

 public partial class Pessoa
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Pessoa()
        {
            this.AlergiasPessoas = new HashSet<AlergiasPessoas>();
        }

        public int ID { get; set; }
        public string nome { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<AlergiasPessoas> AlergiasPessoas { get; set; }
    }
}

In my Create View I get the data from the allergy table in a listbox where the user can select several.

@Html.ListBox("Alergia", (MultiSelectList)ViewBag.Alergia, new { @id = "Fonte", @class = "form-control", @onclick = "teste(this)", @style = "height:150px" })

When sending the data to Concroller by Ubmit, I hope to record both the person and the selected allergies in the Personal Table

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "ID,nome")] Pessoa pessoa, ALGO_QUE_TRAGA_OS_ITENS_SELECIONADOS)
    {
        if (ModelState.IsValid)
        {
            db.Pessoa.Add(pessoa);
            db.SaveChanges();

            foreach (var item in ALGO_QUE_TRAGA_OS_ITENS_SELECIONADOS)
            {
                AlergiasPessoas alergiasPessoas = new AlergiasPessoas();
                alergiasPessoas.ID_Pessoa = pessoa.ID;
                alergiasPessoas.ID_Alergia = item.ID;
                db.AlergiasPessoas.Add(alergiasPessoas);
            }
            db.SaveChanges();

            return RedirectToAction("Index");
        }

        return View(pessoa);
    }

I’m not sure how to receive the selected items in the create action. Any suggestions?

2 answers

3


@Still, @Html.Listbox will pass an array of the selected Ids in the View. You can take it the way you were doing even using a foreach. Change your POST method to... public ActionResult Create([Bind(Include = "ID,nome")] Pessoa pessoa, int[] Alergia)

  • Thank you Daniel!

  • So what is the HTML item’s name to receive in the controller? Type in this example the generated @Html.Listbox ("Allergy". To receive I use Allergy.

1

Hello, one of the ways to do this is by using a Viewmodel, which will move the information from controller to view and return from View to controller. See the link below for a reference on how these components work in detail and an example: Microsoft Docs: Views And Viewmodels

About your case, you can do the following: 1- create a Viewmodel containing a property with the Person class.

2- Reference Viewmodel in view @model ViewModelPessoa

3- Use Viewmodel to load the data into the view and submit the data through a form:

@using (Html.BeginForm())
{
        @Html.ListBoxFor(m => m.Pessoa.AlergiasPessoasSelecionada, m.AlergiasPossiveis, new { id = ListAlergiaPessoas })
        <br />
        <input type="submit" value="Submit" />
}
  • This is the still! And the solution pointed out by @Alexandre is the most elegant, if you are already using the concept of View Model in your project, you can use the solution he pointed out. I personally like this concept very much.

Browser other questions tagged

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