Then I leave the images (1,2). I have the BD "School" which has the Student and Group tables, and I want to add a DropDownList which shows the groups that exist in the BD and select it. I'd appreciate your help.
There are many ways to do it, the easiest is through a ViewBag
Suppose that your Group table is composed as follows.
On your Controller.
ViewBag.Grupos= context.Grupos.Select(x => new { IdGrupo = x.Id, Grupo = x.Grupo}).ToList();
In your view you assign it like that.
@Html.DropDownListFor(m => m.SelectedGrupoId, new SelectList(ViewBag.Grupos, "IdGrupo", "Grupo"), "- Selecciona uno -", new { @class = "form-control" })
I hope it serves you.
For this it is advisable to use viewmodels that allow us to send a customized model to the view.
ViewModel
// Este lo puedes usar para crear y etitar
public class AumnoEditViewModel
{
public int GrupoId { get; set; }
public IEnumerable<Grupo> Grupos{ get; set; }
// Incluir propiedades del alumno
public AlumnoId { get; set; }
public Nombre { get; set; } // Etc
}
Driver
public class AlumnoController : Controller
{
MyContext db = new MyContext();
[HttpGet]
public ActionResult AddOrEdit()
{
var model = new AlumnoEditViewModel();
model.Grupos = db.Grupos.ToList();
return View(model);
}
[HttpPost]
public ActionResult AddOrEdit(AlumnoEditViewModel model)
{
var nuevoAlumno = new Alumno()
{
Nombre = model.Nombre,
GrupoId = model.GrupoId // El Id del grupo seleccionado
};
db.Alumnos.Add(nuevoAlumno);
db.SaveChanges();
return RedirectToAction("Index");
}
}
Vista
@model TuProyecto.Models.AumnoEditViewModel
@using (Html.BeginForm("AddOrEdit", "Alumnos", FormMethod.Post))
{
@Html.AntiForgeryToken()
<div class="form-group">
<input type="text" name="Nombre">
</div>
<div class="form-group">
<select name="GrupoId">
// Llenar las opciones del select
@foreach (var grupo in Model.Grupos)
{
<option value="@grupo.Id">@grupo.Nombre</option>
}
</select>
</div>
}
I hope you serve