How to access specific information inside an Asp.net View Bag

-3

I'm doing a project where we have to create a social network in which the user can post something. After doing post it has to appear what he posted the name and the profile image. For now I have this in the controller:

 var posts_public = from p in db.Posts
   join e in db.Especificars on p.id_post equals e.id_post
   join pu in db.Publicar_Posts on p.id_post equals pu.id_post
   join u in db.Utilizadors on pu.id_utilizador equals u.id_utilizador
   where e.id_privacidade == 1
   select new { p.texto, u.nome, u.apelido, u.imagem_perfil };

 ViewBag.Posts = posts_public;

And in the view I have this:

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

The information that appears is:

{texto = ola, nome = andre, apelido = morais, imagem perfil = /Content/Images/img2

I wanted something like this:

"Imagem do utilizador aqui" André Morais

Ola

But I'm not able to access just the content of the image for example to be able to <img src> and display the image.

    
asked by anonymous 08.12.2015 / 15:59

1 answer

2

The correct way to do this is by creating a ViewModel and typing the View as follows:

var posts_public = from p in db.Posts
                   join e in db.Especificars on p.id_post equals e.id_post
                   join pu in db.Publicar_Posts on p.id_post equals pu.id_post
                   join u in db.Utilizadors on pu.id_utilizador equals u.id_utilizador
                   where e.id_privacidade == 1
                   select new PostViewModel { 
                       Texto = p.texto, 
                       NomeUsuario = u.nome, 
                       Apelido = u.apelido, 
                       ImagemPerfil = u.imagem_perfil 
                   };

return View(posts_public);

View would look like this:

@model IEnumerable<SeuProjeto.ViewModels.PostViewModel>

@foreach (var item in Model)
{
    @item
}
The ViewModel is a simple class:

public class PostViewModel
{
    public String Texto { get; set; }
    public String Nome { get; set; }
    public String Apelido { get; set; }
    public String ImagemPerfil { get; set; }
}
    
08.12.2015 / 16:15