Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display a list using ViewBag

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()"

like image 221
user1274646 Avatar asked May 09 '12 18:05

user1274646


People also ask

Which of the following features are available in a strongly typed view?

In strongly typed view , view is bind with corresponding model class object/objects. Scaffolding Template works based on strongly typed view. It is sacfloding view which is auto generated view. Strongly typed views are used for rendering specific types of model objects.

What is ViewData in MVC?

In MVC, when we want to transfer the data from the controller to view, we use ViewData. It is a dictionary type that stores the data internally. ViewData contains key-value pairs which means each key must be a string in a dictionary.


2 Answers

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.

like image 160
Leniency Avatar answered Sep 20 '22 21:09

Leniency


To put it all together, this is what it should look like:

In the controller:

List<Fund> fundList = db.Funds.ToList(); ViewBag.Funds = fundList; 

Then in the view:

@foreach (var item in ViewBag.Funds) {     <span> @item.FundName </span> } 
like image 20
Chris Avatar answered Sep 17 '22 21:09

Chris