-1

How do you display list of data from two different table in a single view in MVC5 EF?

For example, I have two tables(Project/Proposer) and in Proposer View I have Create, Edit and Details pages. When user clicks on a Details link the page displays the details for that proposer. But, how do I display list of project for that proposer?

This is my current ProposerController:

public ActionResult Details(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Proposer proposer = db.Proposers.Find(id);
    var proposers = db.Proposers.ToList();
    if (proposer == null)
    {
        return HttpNotFound();
    }
    return View(proposer);
}
ekad
  • 14,436
  • 26
  • 44
  • 46
  • You need to specify more details and provide some code samples. – Aleksandr Ivanov Apr 01 '15 at 22:59
  • Hi, Thanks for your reply. sorry about that. I have tried to attached some screenshots but, as I have just resisted with this site it's not allowing me to upload screenshots., Here is some screenshots in below link. http://www.4shared.com/folder/RyXYJDU-/Code.html – Harsh Panchal Apr 02 '15 at 01:17
  • It's your first question so I will try to help you. Please first read [article](http://stackoverflow.com/help/how-to-ask) about good questions. Then when you write the answer you have much more options than plain text. There is a help button for question textbox. You can also edit your existing question. – Aleksandr Ivanov Apr 02 '15 at 08:37
  • @HarshPanchal here read about `ViewModels`, because this question has been asked 1000s of times. http://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc – SOfanatic Apr 02 '15 at 13:05
  • Thanks for your comment but, i have tried using ViewModels but got confuse. – Harsh Panchal Apr 02 '15 at 13:28

2 Answers2

1

Assuming db is your context, you can access your table Project with db.Projects, just like you did with Proposer. Then, just compose a ViewModel as suggested in the comments and display it - voilà.

Thaoden
  • 3,460
  • 3
  • 33
  • 45
1

Your LINQ query should be something like:

var proposer = db.Proposers
    .Include(x => x.Projects)
    .SingleOrDefault(x => x.ID == id);

The Include statement tells Entity Framework to include the Projects data with the same query, resulting in only a single call to the DB.

Then you access the Projects like:

foreach(var project in proposer.Projects)
{
    // Do your stuff
}

That said, I highly recommend you read up some more on ViewModels and best practices on how to pass and/or convert your data into the presentation layer.

Beyers
  • 8,968
  • 43
  • 56