UL LI树,在客户端部分

问题描述 投票:1回答:1

如何基于现有模型构建ul LI树?在应用程序的客户端。可以无限制地访问

@foreach (var item in Model)
{

    <tr>
        <th scope="col">@Html.DisplayFor(modelItem => item.Id) </th>
        @if (item.ParentId != null)
        {
        <th scope="col">@Html.DisplayFor(modelItem => item.ParentTitle) </th>
        }
        else
        {
             <th scope="col">null </th>
        }

        <th scope="col">@Html.DisplayFor(modelItem => item.Title) </th>
        <th scope="col">@Html.DisplayFor(modelItem => item.Description) </th>
        <th scope="col">@Html.DisplayFor(modelItem => item.Created) </th>


    </tr>
}

我看到了一个手动构建,只是标记和获取模型元素,但有可能以某种方式自动化该过程吗?

<ul>
    <li>First parent
      <ul>
        <li>First child
          <ul>

模型:

[Table("TestTable", Schema = "dbo")]
    public class MyClass
    {
        public int Id { get; set; }
        public int? ParentId { get; set; }
        public string Title { get; set; }
        public DateTime Created { get; set; }
        public string Description { get; set; }
    }


    public class MySecondClass
    {
        public int Id { get; set; }
        public int? ParentId { get; set; }
        public string Title { get; set; }
        public DateTime Created { get; set; }
        public string Description { get; set; }
        public string ParentTitle { get; set; }
    }
html asp.net-mvc html5 razor
1个回答
3
投票

我会在你的父级上有一个子属性列表,而不是2个非常相似的类,那么你就可以创建一个层次结构:

public class MyClass
{
    public int Id { get; set; }
    public int? ParentId { get; set; }
    public string Title { get; set; }
    public DateTime Created { get; set; }
    public string Description { get; set; }
    public IEnuerable<MyClass> Children { get; set; }
}

然后,您可以构建层次结构(在下面,我假设Model是您所有项目的列表),而不是通过一组平面类作为您的模型;

var topLevel = Model.Where(item => !item.HasValue); // or whatever the value is when there is no parent

然后你可以遍历这个顶级来设置你的孩子:

foreach (var item in topLevel)
{
    item.Children = GetChildren(item.Id, Model);
}

你的Get Children方法也可以

public static IEnumerable<MyClass> GetChildren(int parentId, IEnumerable<MyClass> allItems)
{
   if (parentId.HasValue)
   {
      var children = allItems.Where(item => item.ParentId.HasValue && item.ParentId.Value.Equals(parentId));
      if (children != null && children.Any())
      {
          foreach (var item in children)
          {
              item.Children = GetChildren(item.Id, allItems);
          }

          return children;
      }
   }

   return null;
}

这应该有助于构建一些东西然后你可以有一个部分采用IEnumerable<MyClass>模型并使其递归:

@model IEnumerable<MyClass>

@foreach (MyClass item in Model)
{
    <ul>
        <li>
           @item.Title
           @if (item.Children != null && item.Children.Any())
           {
               @Html.Partial("NameOfThisPartial", item.Children)
           }
        </li>
    </ul>
}

你最初的部分电话将是:

@Html.Partial("NameOfThisPartial", topLevel)
© www.soinside.com 2019 - 2024. All rights reserved.