Search code examples
c#linqmodel-view-controller.net-coreviewbag

How do i display data passed from viewbag in controller to view


I have tried to display using @(foreach var x in viewbag.data2) loop in view

 var data = from c in _context.Posts
                       join p in _context.PostViewCount on c.Id equals p.PostId
                       select new
                       {
                           posts = c,
                           p.Count,
                           c.Title,
                           p.PostId

                       };
            var dat = data.OrderByDescending(x=>x.Count).ToList();
            ViewBag.data2 = dat;

I m getting invalid operation exception


Solution

  • You got your syntax a little wrong.

    it should be:

    @foreach(var x in ViewBag.data2){
    
        @x.Count
        @x.Title
    
    }
    

    Edit: As there seems to be a little bit of confusion with dynamic types. This example shows how to use a defined model..

    Create a class for your data rather than using an anonymous object.

    public class PostsModel
    {
        public string Title { get; set; }
        public int Count { get; set; }
        // etc...
    }
    

    Modify your query...

    var data = from c in _context.Posts
                       join p in _context.PostViewCount on c.Id equals p.PostId
                       select new PostsModel
                       {
                           Count = p.Count,
                           Title = c.Title,
                           // etc...
                       };
            var dat = data.OrderByDescending(x=>x.Count).ToList();
            ViewBag.data2 = dat;
    

    Then just cast your Viewbag variable to the right type...

    @foreach(PostsModel x in ((IEnumerable<PostsModel>)ViewBag.data2)){
    
        @x.Count
        @x.Title
    
    }
    

    You might have to import the right namespace to your view by using: @using <namespace>