开发者

How to create common menu control for ASP.NET and ASP.NET MVC?

I have integrated ASP.NET and ASP.NET MVC to work together in a single project. here i have to use some controls in common, like: MENU control. These menu's must populate dynamically from the database. Is it possible to create menu's in div by populating the details from the database with the help of jQuery?

How to create common menu control for ASP.NET and ASP.NET MVC? Any suggestions would be appreciate开发者_JS百科d.


  • Get data from server.
  • Convert data into a JSON format
  • Get jQuery to get the JSON data.
  • Use client-side templating to render your menu.


recently I have moved to ASP.NET MVC and I was also interested, how to create menu. I have found only 1 suitable help (http://www.asp.net/mvc/tutorials/providing-website-navigation-with-sitemaps-cs). This tutorial creates menu using Web.sitemap. But if you would try to create the menu with this help, you will see that it is not suitable for "more level" menus. So I have modified this code and created this.

using System.Text;
using System.Web;
using System.Web.Mvc;

public static class MenuHelper
{
    public static MvcHtmlString Menu(this HtmlHelper helper)
    {
        var sb = new StringBuilder();
        sb.Append("<div id='menu'><ul>");

        var topLevelNodes = SiteMap.RootNode.ChildNodes;

        foreach (SiteMapNode node in topLevelNodes)
        {
            sb.AppendLine(SiteMap.CurrentNode == node ? "<li class='selectedMenuItem'>" : "<li>");

            sb.AppendFormat("<a href='{0}'>{1}</a>", node.Url, helper.Encode(node.Title));

            BuildMenu(sb, node);

            sb.AppendLine("</li>");
        }

        sb.AppendLine("</ul></div>");

        return MvcHtmlString.Create(sb.ToString());
    }

    private static StringBuilder BuildMenu(StringBuilder sb, SiteMapNode node)
    {
        if (node.ChildNodes.Count != 0)
        {
            sb.Append("<ul>");
            foreach (SiteMapNode childNode in node.ChildNodes)
            {
                sb.AppendLine(SiteMap.CurrentNode == childNode ? "<li class='selectedMenuItem'>" : "<li>");

                sb.AppendFormat("<a href='{0}'>{1}</a>", childNode.Url, childNode.Title);

                BuildMenu(sb, childNode);

                sb.AppendLine("</li>");
            }

            sb.AppendLine("</ul>");
        }

        return sb;
    }
}

In the View you write only @Html.Menu(). Remember to create Web.sitemap and also insert your pages into. Hope it helps!


Have you looked at TreeView with Menu?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜