简体   繁体   中英

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

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>

To access viewbag write the below code in your view @ViewBag.data2

It will give you the data.

And place the debugger on it. You will understand the rest.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM