How to display a list using ViewBag

2019-01-17 04:00发布

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

7条回答
叼着烟拽天下
2楼-- · 2019-01-17 04:28

This is what i did and It worked...

C#

ViewBag.DisplaylList = listData; 

javascript

var dispalyList= @Html.Raw(Json.Encode(this.ViewBag.DisplaylList));
for(var i=0;i<dispalyList.length; i++){

 var row = dispalyList[i];
 ..............
 ..............

}

查看更多
Luminary・发光体
3楼-- · 2019-01-17 04:37

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>
}
查看更多
Emotional °昔
4楼-- · 2019-01-17 04:39
     //controller  You can use this way

    public ActionResult Index()
    {
      List<Fund> fundList = db.Funds.ToList();
     ViewBag.Funds = fundList;
        return View();
    }




<--View ; You can use this way html-->

@foreach (var item in (List<Fund>)ViewBag.Funds)
{
    <p>@item.firtname</p>
}
查看更多
爱情/是我丢掉的垃圾
5楼-- · 2019-01-17 04:41

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.

查看更多
小情绪 Triste *
6楼-- · 2019-01-17 04:50

Just put a

 List<Person>

into the ViewBag and in the View cast it back to List

查看更多
ゆ 、 Hurt°
7楼-- · 2019-01-17 04:53

simply using Viewbag data as IEnumerable<> list

@{
 var getlist= ViewBag.Listdata as IEnumerable<myproject.models.listmodel>;

  foreach (var item in getlist){   //using foreach
<span>item .name</span>
}

}

//---------or just write name inside the getlist
<span>getlist[0].name</span>
查看更多
登录 后发表回答