问题描述
我有一个类别中的一组项目的嵌套的数据对象。每个类别可以包含子类,并且没有设置限制的子类别的深度。 (文件系统将具有类似的结构。)它看起来是这样的:
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&LT视图类&GT;
。我要输出的类别为一组嵌套的无序列表(&LT; UL&GT;
)模块。我可以巢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视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!