我有一个模型课程,组件和子组件:
public class Course
{
public virtual int CourseId { get; set; }
public virtual string Name { get; set; }
public virtual List<Component> Components { get; set; }
}
public class Component
{
public virtual int ComponentId { get; set; }
public virtual int CourseId { get; set; }
public virtual string Type { get; set; }
public virtual string Name { get; set; }
public virtual Course Course { get; set; }
public virtual List<Subcomponent> Subcomponents { get; set; }
}
public class Subcomponent
{
public virtual int SubcomponentId { get; set; }
public virtual int ComponentId { get; set; }
public virtual string TypeSub { get; set; }
public virtual string NameSub { get; set; }
public virtual int ParentId { get; set; }
public virtual Subcomponent Parent { get; set; }
public virtual List<Subcomponent> Childs { get; set; }
public virtual Component Component { get; set; }
}
子组件具有父子关系,因此每个子组件可以有多个子组件,依此类推。我在视图中有一个表来显示所有组件及其子组件具有不同的级别,但是当我到达子组件时,如果我为该子组件创建一个子组件,它将获得相同的级别。当我的子组件是另一个子组件的子组件时,我该如何创建一个空间或某种东西来区分层次结构?我已经搜索并尝试了很多方法,但没有任何方法适合我。我应该为子组件创建局部视图,然后在主表的视图中调用它吗? 在视图中我有这个:
@model SGP.Models.Course
<div>
<table>
<tr>
...
@foreach (var item in Model.Components)
{
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Type)
</td>
...
@if (item.Subcomponents.Count != 0)
{
<table>
...
@foreach (var x in item.Subcomponents)
{
if (x.ParentId == 0) {
<td>
>>
</td>
...
@foreach (var y in x.Childs) {
<td>
(subsubcomponents and subsubsubcomponents and so on stay in this level always)
>>>>
</td>
...
修改 控制器:
public ActionResult Planificacao(int id = 0)
{
Course course = db.Courses.Find(id);
if (course == null)
{
return HttpNotFound();
}
return View(course);
}
答案 0 :(得分:0)
你绝对可以使用部分视图,我可能会推荐它。我们的想法是创建一个递归循环来遍历Component.Subcomponent
集合,并为每个子组件和它的子组件(Childs)输出一些html
我写了一个@helper,你可以添加到View中,向你展示如何完成它。
@helper BuildSubTree(List<HelloWorldMvcApp.Subcomponent> subcomps) {
if (subcomps != null && subcomps.Any()) {
<table class="table table-bordered">
<thead>
<tr>
<td>Subcomponent Id</td>
<td>Type Sub</td>
<td>Name Sub</td>
<tr>
</thead>
<tbody>
@foreach (var sub in subcomps)
{
<tr>
<td>@sub.SubcomponentId</td>
<td>@sub.TypeSub</td>
<td>@sub.NameSub</td>
</tr>
if (sub.Childs != null && sub.Childs.Any())
{
<tr>
<td colspan="3">@BuildSubTree(sub.Childs)</td>
</tr>
}
}
</tbody>
</table>
}
}
然后在您的视图中,您可以像这样调用此帮助程序。
<table class="table">
<thead>
<tr>
<th>Course ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>@Model.CourseId</td>
<td>@Model.Name</td>
</tr>
@foreach (var comp in Model.Components) {
<tr>
<table class="table table-bordered">
<thead>
<tr>
<th>Component Id</th>
<th>Type</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>@comp.ComponentId</td>
<td>@comp.Type</td>
<td>@comp.Name</td>
</tr>
@if (comp.Subcomponents.Any())
{
<tr>
<td colspan="3">
@BuildSubTree(comp.Subcomponents)
</td>
</tr>
}
</tbody>
</table>
</tr>
}
</tbody>
</table>
我创建了一个DotNetFiddle来向您展示它们如何协同工作。