Greetings, I have a problem with my code in Asp Mvc 5, I have several related models and I have a Listbox that filters the values of a foreign key, but when I try to save it, only a single value is saved, not all the selected ones, and that ultimoes what I need.
This is my code, The Student.cs class
public class Estudiante
{
public int EstudianteId { get; set; }
[Required]
[Display(Name = "Nombre")]
public string nombre { get; set; }
public virtual int MateriaId { get; set; }
public virtual Materia Materia { get; set; }
}
The class Materia, Materia.cs
public class Materia
{
public int MateriaId { get; set; }
[Required]
[Display(Name ="Asignatura")]
public string asignatura { get; set; }
public virtual ICollection<Estudiante> Estudiantes { get; set; }
public virtual int ProfesorId { get; set; }
public virtual Profesor Profesor { get; set; }
}
the Professor.cs class,
public class Profesor
{
public int ProfesorId { get; set; }
[Required]
[Display(Name="Profesor")]
public string name { get; set; }
public virtual ICollection<Materia> Materias { get; set; }
}
And the listbox in the Create, Create.cshtml action.
<div class="form-group">
@Html.LabelFor(model => model.MateriaId, "Materias", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.ListBox("MateriaId",ViewBag.MateriaId as MultiSelectList,new { Multiple="multiple", size = "10"})
@Html.ValidationMessageFor(model => model.MateriaId, "", new { @class = "text-danger" })
</div>
</div>
in the driver, StudentsController.cs
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "EstudianteId,matricula,nombre,apellido,fecha,MateriaId")] Estudiante estudiante)
{
if (ModelState.IsValid)
{
db.Estudiantes.Add(estudiante);
db.SaveChanges();
return RedirectToAction("Index");
}
//get profesor name
ViewBag.MateriaId = new SelectList(db.Materias, "MateriaId", "asignatura", estudiante.MateriaId);
return View(estudiante);
}
and in the index
public ActionResult Index()
{
var estudiantes = db.Estudiantes.Include(e => e.Materia).Distinct().ToList();
return View(estudiantes.ToList());
}
What I need is for the listbox to save all the elements instead of just one. Thanks in advance.