Greetings, I have problems with a DropDownList in ASP.net MVC, the website filters the Teachers but at the time of saving gives the following error:
This is the error that the System shows:
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object. Line 61: ViewBag.ProfessorId = new SelectList (db.Profesors, "TeacherId", "name", subject.ProfessorId);
My Code in the Model: Materia.cs
public class Materia
{
[Key]
public int MateriaId { get; set; }
[Required]
[Display(Name ="Materia")]
public string materia { get; set; }
// public string Profesor { get; set; }
public virtual int ProfesorId { get; set; }
public virtual Profesor Profesor { get; set; }
public virtual ICollection<Estudiante> Estudiantes { get; set; }
}
in Professor.cs
public class Profesor
{
public int ProfesorId { get; set; }
[Required]
public string name { get; set; }
public virtual ICollection<Materia> Materias { get; set; }
}
in the MateriasController.cs driver:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "MateriaId,materia,ProfesorId")] Materia materia)
{
if (ModelState.IsValid)
{
db.Materias.Add(materia);
db.SaveChanges();
return RedirectToAction("Index");
}
if (materia != null)
{
ViewBag.ProfesorId = new SelectList(db.Profesors, "ProfesorId", "name", materia.ProfesorId);
}
return View(materia);
}
in the Create.cshtml view
<div class="form-group">
@Html.LabelFor(model => model.ProfesorId,"Profesor", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("ProfesorId", ViewBag.ProfesorId as IEnumerable<SelectListItem>, "Select Materia", htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model=> model.ProfesorId, "", new { @class = "text-danger" })
</div>
</div>