Problems with DropDownList ASP MVC

2

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>
    
asked by C. Sosa 03.03.2017 в 15:41
source

3 answers

1

We go in parts:

ViewData

It is a dictionary of objects to which you assign information, then this becomes accessible in the view. ViewData is a derivative of the class ViewDataDictionary , which means that you can access it by the syntax of "key / value" or in good Spanish: " password / value ".

ViewBag

The ViewBag object is a "wrapper" to the ViewData object that allows you to create dynamic properties for the ViewBag .

Similarities between ViewBag & ViewData:

  • Help maintain and send controller data to the view.
  • They have a short life, that is, they become null when a redirection happens. This happens because its goal is to provide a communication between controllers and views.
  • Differences between ViewBag & ViewData:

  • ViewData is an object dictionary derived from the ViewDataDictionary class and is accessible using strings as keys or keys.
  • ViewBag uses dynamic properties that take advantage of the new dynamics features in C # 4.0
  • ViewData requires typecasting for complex data types and checking null values to avoid errors.
  • ViewBag does not require typecasting for complex types of data.
  • Now, said the theory, we go with the practice:

    In your controller replace:

    ViewBag.ProfesorId = new SelectList(db.Profesors, "ProfesorId", "name", materia.ProfesorId);
    

    By:

    ViewBag.ProfesorId = db.Profesors.ToList(); //Para asegurarnos que vienen datos.
    

    And in your view, try the following:

    @Html.DropDownList("ProfesorId", new SelectList(ViewBag.ProfesorId, "ProfesorID", "materia"))
    
        
    answered by 03.03.2017 / 17:06
    source
    0

    Change the list type to

    public virtual List<Estudiante> Estudiantes { get; set; }
    
        
    answered by 03.03.2017 в 16:30
    0

    Not the scenario for the use of ViewBag, I would tell you a list in the model of your typed view or else load it by ajax.

    I leave the link to a post that explains how to do it link

    Greetings

        
    answered by 03.03.2017 в 21:18