zoukankan      html  css  js  c++  java
  • 在razor中使用递归,巧用递归

    原文发布时间为:2011-04-20 —— 来源于本人的百度文章 [由搬家工具导入]

    Learning Razor–Writing an Inline Recursive HTML Helper

    Writing an Inline Recursive Html Helper

    The Spark view engine provides you with the ability to define inline macros that allow for recursive calls (Read Louis DeJardin blog on the topic here, and additional documentation here).  These macros are extremely useful for rendering a hierarchical structure such as the one in the following snippet.

    <ul>
      <li>Fuller, Andrew
        <ul>
          <li>Davolio, Nancy</li>
          <li>Leverling, Janet</li>
          <li>Peacock, Margaret</li>
          <li>Buchanan, Steven
            <ul>
              <li>Suyama, Michael</li>
              <li>King, Robert</li>
              <li>Dodsworth, Anne</li>
            </ul>
          </li>
          <li>Callahan, Laura</li>
        </ul>
      </li>
    </ul>

    Now, the Razor view engine allows you to easily build a hierarchical structure by the use of inline HTML helpers that can be called recursively.  The following is a basic snippet of a “Hello World” inline HTML helper, and a call to trigger its functionality.

    @HelloWorld("Roberto!")

    @helper HelloWorld(string name) {
        <h1>Hello World! @name</h1>
    }

    Finally, if we wanted to output the html from the first snippet using Razor we could write the following inline HTML helper.

    @model IEnumerable<OrganizationNodeViewModel>
    @using MVC3.Playground.ViewModels;
    @{
        View.Title = "OrganizationTree";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }

    <h2>OrganizationTree</h2>

    @OrgTree(Model, null);

    @helper OrgTree(IEnumerable<OrganizationNodeViewModel> nodes, int? parentId) {
        if (nodes.Any(n => n.ParentId == parentId)) {
        <ul>
            @foreach (var node in nodes.Where(n => n.ParentId == parentId)) {
                <li>
                    @node.DisplayName
                    @OrgTree(nodes, node.Id)
                </li>
            }
        </ul>
        }
    }

  • 相关阅读:
    Java-对象数组排序
    aoj 0118 Property Distribution
    poj 3009 Curling 2.0
    poj 1979 Red and Black
    AtCoder Regular Contest E
    AtCoder Beginner Contest 102
    AtCoder Beginner Contest 104
    SoundHound Inc. Programming Contest 2018
    poj 3233 Matrix Power Series
    poj 3734 Blocks
  • 原文地址:https://www.cnblogs.com/handboy/p/7163964.html
Copyright © 2011-2022 走看看