C Sharper
C Sharper

Reputation: 8626

Display items from list in viewbag in foreach loop

I have list in ViewBag as ViewBag.allteacherlist. I want to show its element in foreach loop. I've done as follows:

<table>

        @foreach (var item in ViewBag.allteacherlist
            as List <TEAMS_PP.Data.TeacherEval>)
            {         
           <tr><td>    @item.AllTechersList() </td> </tr>

            }

</table>

This is giving me the error object not set to referance of an object. The list does come in ViewBag.allteacherlist

What am I doing wrong?

Code for viewbag:

List<TEAMS_PP.Entity.account> list = new TeacherEval().AllTechersList();
            ViewBag.allteacherlist = list;

Upvotes: 0

Views: 8039

Answers (2)

Andrei V
Andrei V

Reputation: 7506

The ViewBag is dynamic and stores objects as, well.. objects. You need to cast the list to its original type before using it.

<table>
    @foreach (var item in ViewBag.allteacherlist
        as List <TEAMS_PP.Data.TeacherEval>)
        {         
            <tr><td>    @item.AllTechersList() </td> </tr>
        }
</table>

As noted by @MainMa in his answer, you need to specify the correct type in your cast, otherwise you will get null when using the as keyword. In your controller you were creating an object of type List<TEAMS_PP.Entity.account> but in your view you were trying to get an object of type TEAMS_PP.Data.TeacherEval. The as cast result was null.

Upvotes: 1

Arseni Mourzenko
Arseni Mourzenko

Reputation: 52321

as keyword converts a value to a given type, when possible, or null otherwise. The statement:

var result = originalValue as SpecificType;

is similar to:

var result = originalValue is SpecificType ? (SpecificType)originalValue : null;

If ViewBag.allteacherlist is not of type List<TEAMS_PP.Data.TeacherEval> or a type which inherits from List<TEAMS_PP.Data.TeacherEval>, you'll get a null, which would lead to "Object not set to reference of an object" exception.

Remember that collections (Collection<T>), for example, don't inherit from lists. On the other hand, most sets you deal with implement IEnumerable<T>. Unless you use specific features of a List<T>, use IEnumerable<T>. Be as much permissive as possible.

Upvotes: 2

Related Questions