Skip to main content
 首页 » 编程设计

c#之如何在 Asp.Net 中访问 ViewBag 中的数据

2024年02月05日14jirigala

您好,谁能告诉我如何在 Asp.net 中访问 ViewBag 中的数据。我会更好地解释什么。我有一个用户可以发布内容的项目,每个用户都有姓名和图像。然后在用户发帖后应该会看到写的是什么名字姓氏和他的照片。 现在我在 Controller 上有这段代码:

var posts_public = from p in db.Posts 
                               join e in db.Privacy on p.id_post equals e.id_post 
                               join pu in db.Publish on p.id_post equals pu.id_post 
                               join u in db.Users on pu.id_user equals u.id_user 
                               where e.id_privacy== 1 
                               select new { p.text, u.name, u.surname, u.image}; 
 
            ViewBag.Posts = posts_public; 

在 View 中我有这个:

 @foreach (var item in ViewBag.Posts) 
        { 
            @item 
 
        } 

但是我得到的结果是

{text = hello, name = Pedro, Surname = Filipe, image = \Content\Imgs\Img4} 

我想要实现的是这样的:

(image of user) img src="\Content\Imgs\Img4) Pedro Filipe  
Hello 

但我无法分离 viewbag 中的数据。有人能帮我吗? 谢谢

请您参考如下方法:

这就是使用 Razor 语法的方式。

@foreach (var item in ViewBag.Posts) 
{ 
    <div> 
        <img src="@item.image"> 
        <p class="name">@item.name @item.Surname</p> 
        <p class="message">@item.text</p> 
    </div> 
}