ASP.NET MVC 视图中的递归 [英] Recursion in an ASP.NET MVC view

查看:31
本文介绍了ASP.NET MVC 视图中的递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于类别中的一组项目,我有一个嵌套的数据对象.每个类别可以包含子类别,并且子类别的深度没有设置限制.(文件系统将具有类似的结构.)它看起来像这样:

I have a nested data object for a set of items within categories. Each category can contain sub categories and there is no set limit to the depth of sub categories. (A file system would have a similar structure.) It looks something like this:

class category
{
    public int id;
    public string name;
    public IQueryable<category> categories;
    public IQueryable<item> items;
}
class item
{
    public int id;
    public string name;
}

我将一个类别列表作为 IQueryable 传递给我的视图.我想将类别输出为一组嵌套的无序列表 (

    ) 块.我可以嵌套 foreach 循环,但是子类别的深度将受到嵌套 foreach 块数的限制.在 WinForms 中,我使用递归完成了类似的处理来填充 TreeView,但我还没有看到任何在 ASPX MVC 视图中使用递归的示例.

    I am passing a list of categories to my view as IQueryable<category>. I want to output the categories as a set of nested unordered list (<ul>) blocks. I could nest foreach loops, but then the depth of sub categories would be limited by the number of nested foreach blocks. In WinForms, I have done similar processing using recursion to populate a TreeView, but I haven't seen any examples of using recursion within an ASPX MVC view.

    可以在 ASPX 视图中进行递归吗?是否有其他视图引擎包含视图输出的递归?

    Can recursion be done within an ASPX view? Are there other view engines that include recursion for view output?

    推荐答案

    像这样创建你自己的 HtmlHelper 扩展方法:

    Create your own HtmlHelper extension method like so:

    namespace System.Web.Mvc
    {
        public static class HtmlHelperExtensions
        {
            public static string CategoryTree(this HtmlHelper html, IEnumerable<Category> categories)
            {
                string htmlOutput = string.Empty;
    
                if (categories.Count() > 0)
                {
                    htmlOutput += "<ul>";
                    foreach (Category category in Categories)
                    {
                        htmlOutput += "<li>";
                        htmlOutput += category.Name;
                        htmlOutput += html.CategoryTree(category.Categories);
                        htmlOutput += "</li>";
                    }
                    htmlOutput += "</ul>";
                }
    
                return htmlOutput;
            }
        }
    }
    

    你应该问很有趣,因为我昨天刚刚创建了其中一个.

    Funny you should ask because I actually created one of these just yesterday.

    这篇关于ASP.NET MVC 视图中的递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆