Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Hi i need to show a list of data using viewbag.but i am not able to do it.
Please Help me..
I tried this thing:

 ICollection<Learner> list = new HobbyHomeService().FetchLearner();
 ICollection<Person> personlist = new HobbyHomeService().FetchPerson(list);
 ViewBag.data = personlist;

and inside view:

 <td>@ViewBag.data.First().FirstName</td>

But this does not show up the value and gives error saying "Model.Person doesnot contain a defibition for First()"

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
487 views
Welcome To Ask or Share your Answers For Others

1 Answer

In your view, you have to cast it back to the original type. Without the cast, it's just an object.

<td>@((ViewBag.data as ICollection<Person>).First().FirstName)</td>

ViewBag is a C# 4 dynamic type. Entities returned from it are also dynamic unless cast. However, extension methods like .First() and all the other Linq ones do not work with dynamics.

Edit - to address the comment:

If you want to display the whole list, it's as simple as this:

<ul>
    @foreach (var person in ViewBag.data)
    {
        <li>@person.FirstName</li>
    }
</ul>

Extension methods like .First() won't work, but this will.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...