Reputation: 2771
I have tried a lot of things but I can't figure out how to do it. I'm getting a List of objects from my database and I actually want to display all the objects in a view. So i get my list of objects thanks to that function:
List<Contact> ListeContacts = StructureData.DonneListeContact(NumDossier);
Then I pass my list to the ViewBag :
ViewBag.ListeContacts = ListeContacts;
So now I would like to display all the properties of each object in a select in the view, so I tried that way:
<select>
@foreach (System.Data.DataRow Contact in ViewBag.ListeContact)
{
<option>@Html.DisplayName(Contact["nom_contact"].ToString())</option>
}
</select>
But it shows me a "NullReferenceExeption" on the foreach. There are a lot of examples on the net but all are done with EntityFramework so it's simple when using a model data structure. Does somebody has an idea ?
Upvotes: 1
Views: 155
Reputation: 21
You have assign to ViewBag.ListeContacts but take as ViewBag.ListeContact. You have miss the the letter "s" at the end of the variable name.
Then you can cast it back to List as bellow.
List<Contact> ListeContacts = (List<Contact>)ViewBag.ListeContacts
Upvotes: 0
Reputation: 18769
Have you tried:
<select>
@foreach (var contact in ViewBag.ListeContacts)
{
<option>@Html.DisplayName(contact["nom_contact"].ToString())</option>
}
</select>
It looks like you have a list of Contact
and you are trying to get a DataRow
from the collection?
EDIT: Also make sure the property you are referencing exists, i.e. nom_contact
Upvotes: 1