user3274324
user3274324

Reputation: 13

Displaying multiple tables from model in single view

I have two tables TxtComment and Login.

I am displaying image urls from Login table and comments from TxtComment table where username in TxtComment equals username in Login.

I am using Db First approach using entityframework.

How can I concatenate these columns from different tables to one common view? I used ViewBag. I got a result.

Controller

public ActionResult Item(int id)
{  
    FoodContext db = new FoodContext();

    ViewBag.FoodItems = db.FoodItems.Where(row => row.itemid == id);

    ViewBag.TxtComments = (from user in db.TxtComments
                           from ff in db.Logins
                           where ff.username == user.username
                           select new { imgurl = ff.imgurl, txtcmt = user.txtcmt });

    return View();

}

View

@for(var item in ViewBag.TxtComments)
{
    <div>@item</div>
}

The result is {imgurl=http:/sdfsdf,txtcmt=sfsdfsdf}

I need each item seperate. How can I? I tried with @item.imgurl, it says error. Is view bag is better? If not, please help me this need with strongly type view.

Upvotes: 1

Views: 109

Answers (1)

Sam Leach
Sam Leach

Reputation: 12956

Create your own ViewModel instead of putting the model inside the ViewBag.

ViewModel:

public class ViewModel
{
    public List<ImageComment> ImageComments { get; set; }

    public ViewModel()
    {
        ImageComments = new List<ImageComment>();
    }
}

public class ImageComment
{
    public string ImageUrl { get; set; }
    public string Comment { get; set; }
}

Controller Action:

public ViewResult Item(int id)
{
    FoodContext db = new FoodContext();

    List<ImageComment> comments = (from user in db.TxtComments
                                   from ff in db.Logins
                                   where ff.username == user.username
                                   select new ImageComment
                                   { 
                                       ImageUrl = ff.imgurl, 
                                       Comment = user.txtcmt 
                                   }).ToList();

    ViewModel vm = new ViewModel{ ImageComments = comments };     
    return View("MyView", vm);
}

View:

@model ViewModel

@{
    ViewBag.Title = "Comments";
}

@foreach(ImageComment comment in Model.ImageComments)
{
    <p>@comment.Comment</p>
    <img src="@comment.ImageUrl" alt="img" />
}

Upvotes: 3

Related Questions