Aldridge1991
Aldridge1991

Reputation: 1367

MVC data access

I'm quite new in MVC technology. I have set up my project fine and now i'd like to add some functionalities. I have created and linked a database to my project too.

Project table

Id, 
Name,
...

Bug table

Project Id,
Name,
...

In the index view of my controller I can see the whole list of projects, which are clickable. If I press for example project "TEST", i want to show a new page and show only the bugs which match with the project ID of TEST.

I've been all day with this and can't get it to work. How would you do it?

Upvotes: 3

Views: 92

Answers (2)

user5135401
user5135401

Reputation: 218

  1. Starting from the point that I will assume that you know how to scaffold the CRUD views using MVC.
  2. So based on point 1, you have Views [ Create, Edit , List , Details ] for your controller Project [ProjectController]
  3. In the controller Project, you can write an action called BugDetails and you call for @Html.Action("BugDetails,Model.Id) in the view Details

Inside your Project controller

 public ActionResult BugDetails(int id)
 {
     using(var db = new YourDbContext())
     {
          var bugs = db.Bugs.Where(m=> m.ProjectId == id);
          return PartialView(bugs);
     }
 }

BugDetails.cshtml

@model IEnumerable<YourProject.Models.Bug>
<table>
   <tr>
      <th>Bug Name</th>
   </tr>
   @foreach(var bug in Model)
   {
       <tr>
         <td>@bug.Name</td>
       </tr>
   }
</table>

Details.cshtml that is related for Project controller

@model YourProject.Models.Project

//... the details view goes here

@Html.Action("BugDetails","Project",new {id= Model.id}) // Project can be changed depends on how you called your project controller, I assumed that you called it *ProjectController*

The above code will render the related bugs in the details view of the project

I hope this will help you

Upvotes: 2

Alan Macgowan
Alan Macgowan

Reputation: 481

Ok, I'll assume that you have your clasess like this:

public class Project
{   
    [Key]
    public int Id { get; set; }

    public string Name { get; set; }

    ...

    public ICollection<Bug> Bugs{ get; set; }
}

public class Bug
{   
    [Key]
    public int Id { get; set; }

    public string Name { get; set; }

    ...
    public int ProjectId { get; set; }

    [ForeignKey("ProjectId")]
    public virtual Project Project { get; set; }

}

Then to get the collection of bugs for a gven project:

var bugs = _dbContext.Bugs.Where(p => p.ProjectId == id).ToList();

Upvotes: 1

Related Questions