Creating menus dynamically in web application

后端 未结 2 1050
醉酒成梦
醉酒成梦 2020-12-22 01:15

Im creating a web application in asp.net visual studio 2008.. in my application, i have manually created a menu control.. since, the menus changes by needs, i wish to load i

2条回答
  •  忘掉有多难
    2020-12-22 01:47

    Download Source Code Here

    
    
     DataBase Driven Menu
    
    
    
     

    In Code Behind File

    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();
     }
    
    }
    }
    

    Create an TransformXSLT.xsl

    
    
     
     
     
     
     
     
     
    
     
     
     
     
    
     
     
     
     
     
     
     
     
     
     
     
     
    
     
     
     
     
     
     
    
    

    Create Sql Table

    CREATE TABLE [dbo].[Menu](
     [ID] [int] IDENTITY(1,1) NOT NULL,
     [Text] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
     [ToolTip] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
     [NavigateUrl] [varchar](150) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
     [ParentID] [int] NULL)
    

提交回复
热议问题