Note that there are some explanatory texts on larger screens.

plurals
  1. POHierarchical Database Driven Menu in MVC
    primarykey
    data
    text
    <p>I use the code below as an HTMLHelper which gets data from the database and loops over it to display a menu. This is fairly straightforward as you can see however, what if you have a database table using the adjacent model of hierarchies eg/ID, ParentID, OrderID. Easy to see whats going on but recursion is needed to get this data out properly. Is writing a C# recursive function acceptable? If so can someone help me with that? The expected output is something similar to this..</p> <pre><code>&lt;ul&gt; &lt;li&gt;Item1 &lt;ul&gt; &lt;li&gt;SubItem1&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>SQL 2008 has a Hierarchy datatype now so I am not sure if this will help things? </p> <p>I would also like some way of enabling users to decide what goes in a menu for example, a list of items that can go in the menu and then choosing these items and their positions in the hierarchy. Once a saved button is pressed it will store this heirarchy in the database.</p> <p>Am I asking too much, I'm sure this must be quite a common scenario?</p> <p>Here is my HTMLHelper code if anyone wants to use it...</p> <pre><code> public static string Menu(this HtmlHelper helper, int MenuCat) { string menuHTML = "&lt;ul id=\"menu\"&gt;"; var route = helper.ViewContext.RequestContext.RouteData; string currentPageName = route.GetRequiredString("id"); DB db = DB.CreateDB(); //var result = from p in db.WebPages where p.CategoryID == 9 select p; var result = from p in db.WebPages select p; foreach (var item in result) { if (item.Name == currentPageName) { menuHTML += "\n\t&lt;li&gt;" + helper.ActionLink(item.Name, "Details", "Dinner", new { id = item.ID }, new { @class = "selected" }) + "&lt;/li&gt;"; } else { menuHTML += "\n\t&lt;li&gt;" + helper.ActionLink(item.Name, "Details", "Dinner", new { id = item.ID }, null) + "&lt;/li&gt;"; } } menuHTML += "\n&lt;/ul&gt;\n"; return menuHTML; } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload