[英]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 我试图在视图中使用@(viewbag.data2中的foreach var x)循环显示
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. 编辑:由于
dynamic
类型似乎有点混乱。 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... 然后只需将
Viewbag
变量转换为正确的类型即可。
@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>
您可能必须使用以下方法将正确的名称空间导入视图:
@using <namespace>
To access viewbag write the below code in your view @ViewBag.data2 要访问viewbag,请在您的视图@ ViewBag.data2中编写以下代码
It will give you the data. 它将为您提供数据。
And place the debugger on it. 并将调试器放在上面。 You will understand the rest.
您将了解其余内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.