Monday, 15 September 2014

c# - Put all parents into list recursively -



c# - Put all parents into list recursively -

i have category object (fetched ef) has navigational object parent, category.

these category objects maintain recursing until parent null.

what need get:

<ul> <li>highest level category (parent=null)</li> <li> <ul> <li>second highest level category</li> <ul> <li>local category</li> </ul> <ul> </li> </ul>

preferably without ton of string manipulation (because there's ton of classes , other things involved), , purely recursive views. problem is, have no thought how should work. easy if went downwards highest level category, need go instead (backwards).

what have:

@model domain.category @{ viewbag.recursion = (int) viewbag.recursion + 1; } @if (model.parent != null) { @html.partial("_recursivecategory", model.parent) <li> <ul class="categorylist"> <li>@html.actionlink(model.name, "index", "categories", new {model.id, name = model.friendlyname}, null)</li> </ul> </li> } else { <li>@html.actionlink(model.name, "index", "categories", new {model.id, name = model.friendlyname}, null)</li> }

which goes fine sec level there on out, they're in same line.

so, can think of nice solution on how solve this? again, without massive hacks of string concatenation?

you may need tweak ul/li's created, here's view:

@functions{ mvchtmlstring createtree(mvcapplication2.models.category category) { var swriter = new stringwriter(); var author = new system.xml.xmltextwriter(swriter); createtree(category, writer); writer.close(); homecoming new mvchtmlstring(swriter.tostring()); } void createtree(mvcapplication2.models.category category, system.xml.xmlwriter outputwriter) { if (category.parent != null) { createtree(category.parent, outputwriter); } // bubble after recursion outputwriter.writestartelement("ul"); outputwriter.writeelementstring("li", category.title); outputwriter.writestartelement("li"); } } <div> @createtree(viewbag.category) </div>

c# asp.net-mvc entity-framework razor

No comments:

Post a Comment