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

  • 相关阅读:
    微软API集
    如何在Visual Studio.net中让同一解决方案中包含多个不同类型的项目并共享同一命名空间
    总结:Asp.net页面之间传递参数的几种方法
    Javascript 鼠标滑过显示大图的效果
    HttpContext.Current.Session["key"]取值
    数字金额转大写
    整合多个图片到一个pdf
    .net reflector & disassembler
    yacc grammar for a simple shell
    Windows cmd编码
  • 原文地址:https://www.cnblogs.com/handboy/p/7163964.html
Copyright © 2011-2022 走看看