ASP.NET 3.5 C#:使用子菜单创建和显示动态菜单的最佳方法

我通常只用一个转发器创建一个数据表,并在我的代码隐藏中使用所有这些html。 我还没有找到一种动态添加子菜单的简单方法。 有没有人有办法做得更好?

呈现为列表的嵌套列表(

  • 中的

    • 元素)。 使用jQuery菜单插件转换为动态菜单。

      通常,我会为菜单使用服务器控件,为子菜单添加自身副本,使其动态生成。 但是,请考虑缓存它,因为生成速度不快。

      您可以创建xslt文件并动态从数据库中获取记录。

      下载完整源代码

          DataBase Driven Menu   
      using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Xml; using System.Data; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { DataSet ds = new DataSet(); XmlDataSource xmlDataSource = new XmlDataSource(); xmlDataSource.ID = "xmlDataSource"; xmlDataSource.EnableCaching = false; string connStr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=G:\Admin\WebSite28\App_Data\Database.mdf;Integrated Security=True;User Instance=True"; using (SqlConnection conn = new SqlConnection(connStr)) { string sql = "Select ID, Text,NavigateUrl,ParentID from Menu"; SqlDataAdapter da = new SqlDataAdapter(sql, conn); da.Fill(ds); da.Dispose(); }   ds.DataSetName = "Menus"; ds.Tables[0].TableName = "Menu"; DataRelation relation = new DataRelation("ParentChild", ds.Tables["Menu"].Columns["ID"], ds.Tables["Menu"].Columns["ParentID"], true); relation.Nested = true; ds.Relations.Add(relation); xmlDataSource.Data = ds.GetXml(); //Reformat the xmldatasource from the dataset to fit menu into xml format xmlDataSource.TransformFile = Server.MapPath("~/TransformXSLT.xsl"); //assigning the path to start read all MenuItem under MenuItems xmlDataSource.XPath = "MenuItems/MenuItem"; //Finally, bind the source to the Menu1 control Menu1.DataSource = xmlDataSource; Menu1.DataBind(); } } }