-2

i'm a beginner in MVC

I try to display a viewbag in a drop down list.

Here is what I get in my controller :

 public ActionResult TableauPolyvalence()
    {
        List<Batiments> BatimentList = _context.Batiments.ToList();
        ViewBag.BatimentList = new SelectList(BatimentList, "Id_Batiment", "Nom");
        return View();
    }

Here is my view :

  @if (ViewBag.BatimentList != null)
            {
                @Html.DropDownListFor(model => model.Batiment, (SelectList)ViewBag.BatimentList, "-- Sélectionner le bâtiment --", new { @class = "form-control" })
            }

I get the following message error : System.NullReferenceException: 'Object reference not set to an instance of an object.' I tried different way in my View but it doesn't work

Can somoene help me for this please

Progman
  • 16,827
  • 6
  • 33
  • 48
DimitriB
  • 1
  • 1
  • 1
    Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Progman Jun 07 '22 at 14:17
  • it can be throw nullexception for don't send Model to View – Okan Karadag Jun 07 '22 at 14:33
  • check your markup, make sure you dont have duplicate model names – Henry24 Jun 07 '22 at 14:37

1 Answers1

0

It may help if you could show the details of your models and I suppose This error was caused by

ViewBag.BatimentList = new SelectList(BatimentList, "Id_Batiment", "Nom");

when you construct a new selectlist,it takes "Id_Batiment" property as value field and"Nom" property as text filed,if your model don't have the property with the same name ,Text field or Value field will be null,and you'll get the error you've shown

And I tested twice as below, you could see the result:

test1: enter image description here

test2: enter image description here

Ruikai Feng
  • 6,823
  • 1
  • 2
  • 11
  • Thank you very much !! I refered to my database column who was "Id_Batiment" and not in my model who was "IdBatiment" thank you ! – DimitriB Jun 08 '22 at 06:43