Well, I have a simple model for studies. There are 3 tables, Person, Allergy and Person Allergy. Being that a person can have several allergies.
My person template 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 View Create I get the data from the allergy table in a listbox where the user can select multiple.
@Html.ListBox("Alergia", (MultiSelectList)ViewBag.Alergia, new { @id = "Fonte", @class = "form-control", @onclick = "teste(this)", @style = "height:150px" })
When sending the data to the Concroller by submit, I hope to record both the person and the allergies selected in the PersonAllergy 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 action create. Any suggestions?