How to access specific information within a View Bag Asp.net

Asked

Viewed 55 times

-3

I’m doing a project where we have to create a social network where the user can post something. After doing the post It has to appear what he posted his name and profile picture. For now I have it 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 stays:

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

I wanted something like:

"Imagem do utilizador aqui" André Morais

Ola

But I’m not being able to access just for example the content of the image to be able to do the <img src> and show the image.

  • 1

    This is the very wrong way to do it. Why don’t you use a Viewmodel to move the image to the View?

  • @Gypsy Heart Mendez and how I do it I didn’t realize :/

1 answer

2

The right way to do this is to create 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);

To View would be so:

@model IEnumerable<SeuProjeto.ViewModels.PostViewModel>

@foreach (var item in Model)
{
    @item
}

To 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; }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.