在树状视图中仅显示一个包含多个文件的类别

Display only one category with mutliple files in treeview

我有一个树状视图,其中显示了类别及其附带的文件。我 运行 的是每个类别都显示多次并显示每次上传时添加的新文件。我想要做的是显示一次类别,然后显示它下面的每个项目。

我尝试将 foreach 移动到文件 link 的正上方,但后来我不知道如何显示类别名称。

这是我当前的标记

<div role="tabpanel" class="tab-pane" id="tree">
    @if (Model.Collaboration.Files.Any())
    {
        foreach (var file in Model.Collaboration.Files)
        {
            <div class="treeview">
                <ul>
                    <li>
                        <input type="checkbox" />
                        <label>
                            @if (file.Category != null)
                            {
                                <span>@file.Category.Name</span>
                            }
                            else
                            {
                                <span>Uncategorized</span>
                            }                                         
                        </label>
                        <ul>
                            <li>
                                @Html.ActionLink(file.Filename, "ShowFile", "Attachments", new { @id = file.Id, collaborationId = Model.Collaboration.Id }, new { target = "_blank" })
                            </li>
                        </ul>
                    </li>
                </ul>
            </div>
        }
    }
</div>

我的模型

public class AttachmentCategory
{
    [DataMember]
    public string Name { get; set; }

    [DataMember]
    public string Description { get; set; }
}    

虽然您可以在视图中包含条件语句以将 category.Name 属性 存储在变量中,并在每次迭代中测试 category.Name 是否与存储的值匹配(并且如果有,请省略 <label> 标签)这会相当混乱,并且还需要您的文件按 category.Name 排序。解决这个问题的最简单方法是使用一个视图模型来表示您想要显示的内容。您没有显示所有模型的全部细节,所以这是一个简化的示例

public class FileVM
{
  public int ID { get; set; }
  public string Name { get; set; }
}

public class CategoryVM
{
  public string ID { get; set; }
  public string Name { get; set; }
  public IEnumerable<FileVM> Files { get; set; }
}

然后在控制器中

public ActionResult Details()
{
  List<CategoryVM> model = new List<CategoryVM>();
  // populate your collection of categories, and for each category, populate its collection of files
  return View(model);
}

查看

@model IEnumerable<CategoryVM>
<ul>
  @foreach(CategoryVM category in Model)
  {
    <li>
      <span>@Html.DisplayFor(m => category.Name)</span>
      <ul>
        @foreach(FileVM file in category.Files)
        {
          <li>
            @Html.ActionLink(file.Filename, "ShowFile", "Attachments", new { id = file.ID, collaborationId = category.ID }, new { target = "_blank" })
          </li>
        }
      </ul>
    <li>
  }
<ul>

旁注:

  1. 不确定复选框的用途(它没有 name 属性,所以 不会 post 支持任何东西)
  2. 使用 <label> 标签没有意​​义 - 它与 任何控件,所以它不是真正的标签。
  3. 最好将"Uncategorized"分配给 CategoryVM.Name 属性 where apropriate 而不是使用 视图中不必要的 if 语句。