Get data from two tables(join) with linq and return result into view

I have two tables: Projects and ProjectsData and I want to execute query with join and get the result in the View.

In the Controller I have this code:

ViewBag.projectsData = (from pd in db.ProjectsData
                                   join p in db.Projects on pd.ProjectId equals p.ID
                                   where pd.UserName == this.HttpContext.User.Identity.Name 
                                   orderby p.Name, p.ProjectNo
                                   select new { ProjectData = pd, Project = p });

What I should use in the View to extract this data. I tried that:

@foreach (var item in ViewBag.projectsData)
{
    @item.pd.UserName
}

but it doesn’t work…

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

In your view you are trying to access a pd property but such property doesn’t exist. The property is called ProjectData.

This being said I would strongly recommend you to use view models and strongly typed views instead of ViewBag. This way you will also get Intellisense in your view which would have helped you pick the correct names.

So you could start by defining a view model that will hold all the information your view would need:

public class MyViewModel
{
    public ProjectData ProjectData { get; set; }
    public Project Project { get; set; }
}

and then inside your controller action populate this view model and pass to the view:

public ActionResult Index()
{
    var viewModel = 
        from pd in db.ProjectsData
        join p in db.Projects on pd.ProjectId equals p.ID
        where pd.UserName == this.HttpContext.User.Identity.Name 
        orderby p.Name, p.ProjectNo
        select new MyViewModel { ProjectData = pd, Project = p };
    return View(viewModel);
}

and finally inside your strongly typed view use the view model:

@model IEnumerable<AppName.Models.MyViewModel>
@foreach (var item in Model)
{
     <div>@item.ProjectData.UserName</div>
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x