MVC data access
I am very new to MVC technology. I set up my project perfectly and now I would like to add some functionality. I created and linked a database to my project.
Projects table
Id, Name, ...
Error table
Project Id,
Name,
...
In the index view of my controller, I see the entire list of projects that can be clicked. If I click for example the "TEST" project, I want to show a new page and only show errors that match the project ID TEST.
I've been with this all day and can't get it to work. How do you do it?
source to share
- Starting from the point where I assume you know how to colorize CRUD views using MVC.
- So, based on point 1, you have Views [Create, Edit, List, Details] for your controller Project [ProjectController]
- In the controller project you can write an action named BugDetails and call
@Html.Action("BugDetails,Model.Id)
in the viewDetails
Inside the 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 associated with the 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 display related errors in the project details view
I hope this helps you
source to share
Ok, I assume you have your classics:
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 a collection of errors for a gven project:
var bugs = _dbContext.Bugs.Where(p => p.ProjectId == id).ToList();
source to share