1

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 ?

4

2 回答 2

1

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

于 2013-08-01T08:17:14.903 回答
0

您已分配给 ViewBag.ListeContacts,但作为 ViewBag.ListeContact。您错过了变量名末尾的字母“s”。

然后你可以将它转换回列表,如下所示。

List<Contact> ListeContacts = (List<Contact>)ViewBag.ListeContacts
于 2013-08-02T07:53:48.567 回答