ASP.NET funkcja rekurencyjna MVC 3
Ok, więc chcę wyświetlić listę zawierającą listy list...
Nie wiem, ile poziomów jest do wyświetlenia, więc pomyślałem, że to jest miejsce, w którym wyłamuję starą rutynę rekurencyjną.
Mam problem z tym, jak to zrobić.Oto co mam do tej pory (w widoku-uproszczone):
@foreach(MyObject item in @Model.ListOfObjects){
<div> @item.Title </div>
//Call recursive function?
}
Teraz każdy z tych obiektów ma również listę
Myślałem, że funkcja brzytwy byłaby tutaj, ale potrzebuję pomocy w jej uformowaniu. Oto moje myślenie:
@functions{
public static void ShowSubItems(MyObject _object){
if(_object.ListOfObjects.Count>0){
foreach(MyObject subItem in _object.listOfObjects){
// Show subItem in HTML
ShowSubItems(subItem);
}
}
}
}
Ale jak widzisz, po prostu potrzebuję pomocy:)
69
Author: Peter Mortensen, 2011-06-21
2 answers
Silnik widoku Razor pozwala pisać rekurencyjne helpery inline za pomocą słowa kluczowego @helper
.
@helper ShowTree(IEnumerable<Foo> foos)
{
<ul>
@foreach (var foo in foos)
{
<li>
@foo.Title
@if (foo.Children.Any())
{
@ShowTree(foo.Children)
}
</li>
}
</ul>
}
186
Author: Paolo Moretti,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-30 09:26:06
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-30 09:26:06
Myślę, że najlepiej jest utworzyć helper HTML do tego celu. Coś takiego:
public static string ShowSubItems(this HtmlHelper helper, MyObject _object)
{
StringBuilder output = new StringBuilder();
if(_object.ListOfObjects.Count > 0)
{
output.Append("<ul>");
foreach(MyObject subItem in _object.listOfObjects)
{
output.Append("<li>");
output.Append(_object.Title);
output.Append(html.ShowSubItems(subItem.listOfObjects);
output.Append("</li>")
}
output.Append("</ul>");
}
return output.ToString();
}
Więc nazwij to tak:
@foreach(MyObject item in @Model.ListOfObjects){
<div> @item.Title </div>
@html.ShowSubItems(item)
}
12
Author: Edwin de Koning,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-09 04:57:05
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-09 04:57:05