How to display a list using ViewBag

前端 未结 9 2032
孤街浪徒
孤街浪徒 2020-12-05 03:07

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 list = ne         


        
相关标签:
9条回答
  • 2020-12-05 03:14

    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>
    }
    
    0 讨论(0)
  • 2020-12-05 03:16

    Use as variable to cast the Viewbag data to your desired class in view.

    @{
    
    IEnumerable<WebApplication1.Models.Person> personlist = ViewBag.data as
    IEnumerable<WebApplication1.Models.Person>;
    // You may need to write WebApplication.Models.Person where WebApplication.Models is
      the namespace name where the Person class is defined. It is required so that view 
      can know about the class Person. 
    }
    

    In view write this

    <td>
        @(personlist.FirstOrDefault().Name)
    </td>
    
    0 讨论(0)
  • 2020-12-05 03:17

    I had the problem that I wanted to use my ViewBag to send a list of elements through a RenderPartial as the object, and to this you have to do the cast first, I had to cast the ViewBag in the controller and in the View too.

    In the Controller:

    ViewBag.visitList = (List<CLIENTES_VIP_DB.VISITAS.VISITA>)                                                                 
    visitaRepo.ObtenerLista().Where(m => m.Id_Contacto == id).ToList()
    

    In the View:

    List<CLIENTES_VIP_DB.VISITAS.VISITA> VisitaList = (List<CLIENTES_VIP_DB.VISITAS.VISITA>)ViewBag.visitList ;
    
    0 讨论(0)
  • 2020-12-05 03:23

    Just put a

     List<Person>
    

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

    0 讨论(0)
  • 2020-12-05 03:28

    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>
    
    0 讨论(0)
  • 2020-12-05 03:29

    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.

    0 讨论(0)
提交回复
热议问题