asp.net菜单控件中xmldatasource的替代方法

时间:2011-02-11 08:43:28

标签: c# asp.net xmldatasource

我的代码如下

DataSet ds = new DataSet();
        string connStr = "Data Source=PARITAS00024;Initial Catalog=MenuDb;Persist Security Info=True;User ID=sa;Password=paritas123";
        using (SqlConnection conn = new SqlConnection(connStr))
        {
            string sql = "Select MenuId, MenuTitle, MenuDesc, MenuURL, ParentMenuId from tblMenus where Status=1 and RecordStatus=1 order by ParentMenuId, DisplayOrder";
            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["MenuId"], ds.Tables["Menu"].Columns["ParentMenuId"], true);

        relation.Nested = true;
        ds.Relations.Add(relation);

        System.Web.UI.WebControls.XmlDataSource xds = new System.Web.UI.WebControls.XmlDataSource();
        xds.TransformFile = "~/TransformXSLT.xsl";
        xds.XPath = "MenuItems/MenuItem";
        xds.Data = ds.GetXml();
        xds.ID = "xmlDataSourceMenu";

        Menu1.DataSource = xds;
        Menu1.DataBind();

这是使用xmldatasource的正确方法吗?

2 个答案:

答案 0 :(得分:1)

使用数据源的优势与声明性编程有关:将重点从必须完成的工作转移到结果。如果您以强制方式使用数据源,则会失去所有优势。

在该代码中,您将为您的菜单提供一些XML数据,这些数据通过XSL转换转换查询返回的DataSet的XML表示:您真的需要做所有这些工作吗?

为什么不以编程方式填充菜单?

  foreach (DataRow parentItem in ds.Tables[0].Rows)
  {
    MenuItem item = new MenuItem((string)parentItem["Name"]);
    menu.Items.Add(categoryItem);

    ...
  }

或者,为什么不在aspx中使用XmlDataSource:

<asp:XmlDataSource TransformFile="~/TransformXSLT.xsl" XPath="MenuItems/MenuItem" ID="xmlDataSourceMenu" runat="server" />

,在代码背后:

...
xmlDataSourceMenu.Data = ds.GetXml();
...

答案 1 :(得分:0)

try
{
    XmlDocument xdoc = new XmlDocument();    
    SqlConnection cnn = null;    
    SqlCommand cmd = null;    

    // connection string from web.config
    cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["____"].ConnectionString);
    cnn.Open();

    // SP must return hierarchy of menu items.
    string strUSP = "USP_XMLStoredProcedureName"; 
    cmd = new SqlCommand(strUSP, cnn);

    XmlReader reader = cmd.ExecuteXmlReader();

    if (reader.Read()) { xdoc.Load(reader); }

    // DRAG AND DROP XMLDataSource from toolbox , provide id as "DataSourceXML"
    DataSourceXML.Data = xdoc.InnerXml.ToString();

    // To avoid root
    DataSourceXML.XPath = "/ParentMenu/SubMenu";

    // :: Provide XMLDatasource ID to Menucontrol.

    // OR
    XmlDataSource XDS = new XmlDataSource();
    XDS.ID = "XMLDataSourceID";
    XDS.Data= xdoc.InnerXml;

    // To avoid root
    XDS.XPath = "/ParentMenu/SubMenu";

    MyMenu.DataSource = XDS;
    MyMenu.DataBind();

}
catch (Exception ex)
{
    throw ex;
}
finally
{
    cmd.Dispose();
    cnn.Close();
}