UL LI树,在客户端部分

时间:2018-03-06 14:05:30

标签: html asp.net-mvc html5 razor

如何基于现有模型构建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; }
    }

1 个答案:

答案 0 :(得分:3)

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

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);
}

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

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;
}

你的Get Children方法可以

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)

您最初的部分电话将是:

from multiprocessing.dummy import Pool

with Pool(300) as pool:
    map_res = pool.map_async(f, [2, 10])
    res = map_res.get(timeout=1)