如何使用 asp.net 4.0 和 JavaScript 绘制分层菜单控件
How to draw hierarchical menu control with asp.net 4.0 with JavaScript
我正在处理一封新闻信 system.I 我想知道如何使用 JavaScript 绘制分层菜单控件,这里是 article。
我尝试按原样设置我的代码:
App_Code / SooperFish.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
using System.Net.Mail;
using System.Data;
using System.Data.SqlClient;
using System.Net;
/// <summary>
/// Summary description for NlevelMenu
/// </summary>
public class SooperFish
{
string ConnectionString, ErrorMsg;
public object ApiProcedure { get; private set; }
public CredentialCache Credentials { get; private set; }
public SooperFish()
{
//Read Connection String From web.config
ConnectionString = WebConfigurationManager.ConnectionStrings["EASYMAILConnectionString"].ConnectionString;
}
public string GenerateXmlFormat()
{
string SqlCommand;
DataSet DbMenu;
DataRelation relation;
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
SqlCommand = "SELECT[MenuID],[MenuName],[MenuLocation],[ParentMenuID] FROM [EASYMAIL].[dbo].[tbl_Menu_master] WHERE [type_id] = " + int.Parse(HttpContext.Current.Session["TypeID"].ToString()) + " AND [IsActive] = 1 ";
DbMenu = new DataSet();
SqlDataAdapter Adapter = new SqlDataAdapter(SqlCommand, conn);
Adapter.Fill(DbMenu);
Adapter.Dispose();
}
DbMenu.DataSetName = "Menus";
DbMenu.Tables[0].TableName = "Menu";
//create Relation Parent and Child
relation = new DataRelation("ParentChild", DbMenu.Tables["Menu"].Columns["MenuID"], DbMenu.Tables["Menu"].Columns["ParentMenuID"], true);
relation.Nested = true;
DbMenu.Relations.Add(relation);
return DbMenu.GetXml();
}
public string ExecuteXSLTransformation()
{
string HtmlTags, XsltPath;
MemoryStream DataStream = default(MemoryStream);
StreamReader streamReader = default(StreamReader);
try
{
//Path of XSLT file
XsltPath = HttpContext.Current.Server.MapPath("XsltFormatFolder/XsltTransformer.xslt");
//Encode all Xml format string to bytes
byte[] bytes = Encoding.ASCII.GetBytes(GenerateXmlFormat());
DataStream = new MemoryStream(bytes);
//Create Xmlreader from memory stream
XmlReader reader = XmlReader.Create(DataStream);
// Load the XML
XPathDocument document = new XPathDocument(reader);
XslCompiledTransform XsltFormat = new XslCompiledTransform();
// Load the style sheet.
XsltFormat.Load(XsltPath);
DataStream = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(DataStream, Encoding.ASCII);
//Apply transformation from xml format to html format and save it in xmltextwriter
XsltFormat.Transform(document, writer);
streamReader = new StreamReader(DataStream);
DataStream.Position = 0;
HtmlTags = streamReader.ReadToEnd();
return HtmlTags;
}
catch (Exception ex)
{
ErrorMsg = ex.Message;
return ErrorMsg;
}
finally
{
//Release the resources
streamReader.Close();
DataStream.Close();
}
}
}
MenuControl.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="MenuControl.ascx.cs" Inherits="MenuControl"%>
<link rel="stylesheet" type="text/css" href="css/sooperfish.css" media="screen"/>
<link rel="stylesheet" type="text/css" href="css/sooperfish-theme-large.css" media="screen"/>
<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="js/jquery.easing-sooper.js"></script>
<script type="text/javascript" src="js/jquery.sooperfish.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('ul.sf-menu').sooperfish();
});
</script>
<asp:Literal ID="Literal1" runat="server"></asp:Literal>
菜单控件代码
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Data.SqlClient;
using System.Text;
using AjaxControlToolkit;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using ICSharpCode.SharpZipLib.Zip;
using System.Collections.Specialized;
using System.Data.OleDb;
using System.Net.Mail;
using System.Data.Linq.SqlClient;
using OpenPop.Pop3;
using OpenPop.Mime;
using OpenPop.Mime.Header;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Resolvers;
public partial class MenuControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SooperFish spoorfishMenu = new SooperFish();
Literal1.Text = spoorfishMenu.ExecuteXSLTransformation();
}
}
}
这怎么解决不了我的问题,因为网络请求时发生 500 内部错误。
好的。在不使用网络请求的情况下通过这段代码解决了问题;
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Data.SqlClient;
using System.Text;
public partial class MenuControl : System.Web.UI.UserControl
{
protected void Page_Init(object sender, EventArgs e)
{
Menu1.MenuItemClick += new MenuEventHandler(Menu1_MenuItemClick);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
PopulateMenu(this.GetData(), 0, null);
}
}
public DataTable GetData(int parentMenuId)
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("MenuID", typeof(int)));
dt.Columns.Add(new DataColumn("MenuName", typeof(string)));
dt.Columns.Add(new DataColumn("MenuLocation", typeof(string)));
using (DataClassesDataContext db = new DataClassesDataContext())
{
var menu = db.Menus.Where(m => m.ParentMenuID.Equals(parentMenuId) && m.IsActive.Equals(true)).Select(m => new { MenuID = m.MenuID, MenuTitle = m.MenuName, MenulLocation = m.MenuLocation }).ToList();
foreach (var menuItem in menu)
{
if (menuItem != null)
{
DataRow dr = dt.NewRow();
dr["MenuID"] = menuItem.MenuID;
dr["MenuName"] = menuItem.MenuTitle.ToString();
dr["MenuLocation"] = menuItem.MenulLocation.ToString();
dt.Rows.Add(dr);
}
}
}
return dt;
}
public void PopulateMenu(DataTable dt, int parentMenuId, MenuItem parentMenuItem)
{
string currentPage = Path.GetFileName(Request.Url.AbsolutePath);
foreach (DataRow row in dt.Rows)
{
MenuItem menuItem = new MenuItem { Value = row["MenuID"].ToString(), Text = row["MenuName"].ToString(), NavigateUrl = row["MenuLocation"].ToString(), Selected = row["MenuLocation"].ToString().EndsWith(currentPage, StringComparison.CurrentCultureIgnoreCase) };
if (parentMenuId == 0)
{
Menu1.Items.Add(menuItem);
DataTable dtChild = this.GetData(int.Parse(menuItem.Value));
PopulateMenu(dtChild, int.Parse(menuItem.Value), menuItem);
}
else
{
parentMenuItem.ChildItems.Add(menuItem);
}
}
}
public DataTable GetData()
{
using (DataClassesDataContext db = new DataClassesDataContext())
{
DataTable dt = new DataTable("Menu");
dt.Columns.Add(new DataColumn("MenuID", typeof(int)));
dt.Columns.Add(new DataColumn("MenuName", typeof(string)));
dt.Columns.Add(new DataColumn("MenuLocation", typeof(string)));
dt.Columns.Add(new DataColumn("ParentMenuID", typeof(int)));
DataRow dr = dt.NewRow();
dr["MenuID"] = "1";
dr["MenuName"] = "Home";
dr["MenuLocation"] = "~/User_Landing_Page.aspx";
dt.Rows.Add(dr);
foreach (var item in db.Menus.Where(m => m.IsActive.Equals(true) && m.type_id.Equals(int.Parse(Session["TypeID"].ToString())) && m.ParentMenuID == null).Select(m => new
{
MenuID = m.MenuID,
MenuName = m.MenuName,
MenuLocation = m.MenuLocation,
ParentMenuID = m.ParentMenuID
}).ToList())
{
if (item != null)
{
DataRow dr1 = dt.NewRow();
dr1["MenuID"] = int.Parse(item.MenuID.ToString());
dr1["MenuName"] = item.MenuName.ToString();
if (item.MenuLocation != null)
{
dr1["MenuLocation"] = item.MenuLocation.ToString();
}
if (item.ParentMenuID != null)
{
dr1["ParentMenuID"] = int.Parse(item.ParentMenuID.ToString());
}
else
{
dr1["ParentMenuID"] = 0;
}
dt.Rows.Add(dr1);
}
}
return dt;
}
}
protected void Menu1_MenuItemClick(object sender, MenuEventArgs e)
{
switch (e.Item.Selected.ToString())
{
case "Compose Mail":
Session["flag"] = "1";
Response.Redirect(e.CommandArgument.ToString());
break;
case "From User Master":
Session["flag"] = "2";
Response.Redirect(e.CommandArgument.ToString());
break;
case "Subscriber Master":
Session["flag"] = "3";
Response.Redirect(e.CommandArgument.ToString());
break;
case "Import Susbcribers":
Session["flag"] = "4";
Response.Redirect(e.CommandArgument.ToString());
break;
default:
Session["flag"] = "0";
Response.Redirect(e.CommandArgument.ToString());
break;
}
}
}
我正在处理一封新闻信 system.I 我想知道如何使用 JavaScript 绘制分层菜单控件,这里是 article。
我尝试按原样设置我的代码:
App_Code / SooperFish.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
using System.Net.Mail;
using System.Data;
using System.Data.SqlClient;
using System.Net;
/// <summary>
/// Summary description for NlevelMenu
/// </summary>
public class SooperFish
{
string ConnectionString, ErrorMsg;
public object ApiProcedure { get; private set; }
public CredentialCache Credentials { get; private set; }
public SooperFish()
{
//Read Connection String From web.config
ConnectionString = WebConfigurationManager.ConnectionStrings["EASYMAILConnectionString"].ConnectionString;
}
public string GenerateXmlFormat()
{
string SqlCommand;
DataSet DbMenu;
DataRelation relation;
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
SqlCommand = "SELECT[MenuID],[MenuName],[MenuLocation],[ParentMenuID] FROM [EASYMAIL].[dbo].[tbl_Menu_master] WHERE [type_id] = " + int.Parse(HttpContext.Current.Session["TypeID"].ToString()) + " AND [IsActive] = 1 ";
DbMenu = new DataSet();
SqlDataAdapter Adapter = new SqlDataAdapter(SqlCommand, conn);
Adapter.Fill(DbMenu);
Adapter.Dispose();
}
DbMenu.DataSetName = "Menus";
DbMenu.Tables[0].TableName = "Menu";
//create Relation Parent and Child
relation = new DataRelation("ParentChild", DbMenu.Tables["Menu"].Columns["MenuID"], DbMenu.Tables["Menu"].Columns["ParentMenuID"], true);
relation.Nested = true;
DbMenu.Relations.Add(relation);
return DbMenu.GetXml();
}
public string ExecuteXSLTransformation()
{
string HtmlTags, XsltPath;
MemoryStream DataStream = default(MemoryStream);
StreamReader streamReader = default(StreamReader);
try
{
//Path of XSLT file
XsltPath = HttpContext.Current.Server.MapPath("XsltFormatFolder/XsltTransformer.xslt");
//Encode all Xml format string to bytes
byte[] bytes = Encoding.ASCII.GetBytes(GenerateXmlFormat());
DataStream = new MemoryStream(bytes);
//Create Xmlreader from memory stream
XmlReader reader = XmlReader.Create(DataStream);
// Load the XML
XPathDocument document = new XPathDocument(reader);
XslCompiledTransform XsltFormat = new XslCompiledTransform();
// Load the style sheet.
XsltFormat.Load(XsltPath);
DataStream = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(DataStream, Encoding.ASCII);
//Apply transformation from xml format to html format and save it in xmltextwriter
XsltFormat.Transform(document, writer);
streamReader = new StreamReader(DataStream);
DataStream.Position = 0;
HtmlTags = streamReader.ReadToEnd();
return HtmlTags;
}
catch (Exception ex)
{
ErrorMsg = ex.Message;
return ErrorMsg;
}
finally
{
//Release the resources
streamReader.Close();
DataStream.Close();
}
}
}
MenuControl.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="MenuControl.ascx.cs" Inherits="MenuControl"%>
<link rel="stylesheet" type="text/css" href="css/sooperfish.css" media="screen"/>
<link rel="stylesheet" type="text/css" href="css/sooperfish-theme-large.css" media="screen"/>
<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="js/jquery.easing-sooper.js"></script>
<script type="text/javascript" src="js/jquery.sooperfish.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('ul.sf-menu').sooperfish();
});
</script>
<asp:Literal ID="Literal1" runat="server"></asp:Literal>
菜单控件代码
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Data.SqlClient;
using System.Text;
using AjaxControlToolkit;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using ICSharpCode.SharpZipLib.Zip;
using System.Collections.Specialized;
using System.Data.OleDb;
using System.Net.Mail;
using System.Data.Linq.SqlClient;
using OpenPop.Pop3;
using OpenPop.Mime;
using OpenPop.Mime.Header;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Resolvers;
public partial class MenuControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SooperFish spoorfishMenu = new SooperFish();
Literal1.Text = spoorfishMenu.ExecuteXSLTransformation();
}
}
}
这怎么解决不了我的问题,因为网络请求时发生 500 内部错误。
好的。在不使用网络请求的情况下通过这段代码解决了问题;
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Data.SqlClient;
using System.Text;
public partial class MenuControl : System.Web.UI.UserControl
{
protected void Page_Init(object sender, EventArgs e)
{
Menu1.MenuItemClick += new MenuEventHandler(Menu1_MenuItemClick);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
PopulateMenu(this.GetData(), 0, null);
}
}
public DataTable GetData(int parentMenuId)
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("MenuID", typeof(int)));
dt.Columns.Add(new DataColumn("MenuName", typeof(string)));
dt.Columns.Add(new DataColumn("MenuLocation", typeof(string)));
using (DataClassesDataContext db = new DataClassesDataContext())
{
var menu = db.Menus.Where(m => m.ParentMenuID.Equals(parentMenuId) && m.IsActive.Equals(true)).Select(m => new { MenuID = m.MenuID, MenuTitle = m.MenuName, MenulLocation = m.MenuLocation }).ToList();
foreach (var menuItem in menu)
{
if (menuItem != null)
{
DataRow dr = dt.NewRow();
dr["MenuID"] = menuItem.MenuID;
dr["MenuName"] = menuItem.MenuTitle.ToString();
dr["MenuLocation"] = menuItem.MenulLocation.ToString();
dt.Rows.Add(dr);
}
}
}
return dt;
}
public void PopulateMenu(DataTable dt, int parentMenuId, MenuItem parentMenuItem)
{
string currentPage = Path.GetFileName(Request.Url.AbsolutePath);
foreach (DataRow row in dt.Rows)
{
MenuItem menuItem = new MenuItem { Value = row["MenuID"].ToString(), Text = row["MenuName"].ToString(), NavigateUrl = row["MenuLocation"].ToString(), Selected = row["MenuLocation"].ToString().EndsWith(currentPage, StringComparison.CurrentCultureIgnoreCase) };
if (parentMenuId == 0)
{
Menu1.Items.Add(menuItem);
DataTable dtChild = this.GetData(int.Parse(menuItem.Value));
PopulateMenu(dtChild, int.Parse(menuItem.Value), menuItem);
}
else
{
parentMenuItem.ChildItems.Add(menuItem);
}
}
}
public DataTable GetData()
{
using (DataClassesDataContext db = new DataClassesDataContext())
{
DataTable dt = new DataTable("Menu");
dt.Columns.Add(new DataColumn("MenuID", typeof(int)));
dt.Columns.Add(new DataColumn("MenuName", typeof(string)));
dt.Columns.Add(new DataColumn("MenuLocation", typeof(string)));
dt.Columns.Add(new DataColumn("ParentMenuID", typeof(int)));
DataRow dr = dt.NewRow();
dr["MenuID"] = "1";
dr["MenuName"] = "Home";
dr["MenuLocation"] = "~/User_Landing_Page.aspx";
dt.Rows.Add(dr);
foreach (var item in db.Menus.Where(m => m.IsActive.Equals(true) && m.type_id.Equals(int.Parse(Session["TypeID"].ToString())) && m.ParentMenuID == null).Select(m => new
{
MenuID = m.MenuID,
MenuName = m.MenuName,
MenuLocation = m.MenuLocation,
ParentMenuID = m.ParentMenuID
}).ToList())
{
if (item != null)
{
DataRow dr1 = dt.NewRow();
dr1["MenuID"] = int.Parse(item.MenuID.ToString());
dr1["MenuName"] = item.MenuName.ToString();
if (item.MenuLocation != null)
{
dr1["MenuLocation"] = item.MenuLocation.ToString();
}
if (item.ParentMenuID != null)
{
dr1["ParentMenuID"] = int.Parse(item.ParentMenuID.ToString());
}
else
{
dr1["ParentMenuID"] = 0;
}
dt.Rows.Add(dr1);
}
}
return dt;
}
}
protected void Menu1_MenuItemClick(object sender, MenuEventArgs e)
{
switch (e.Item.Selected.ToString())
{
case "Compose Mail":
Session["flag"] = "1";
Response.Redirect(e.CommandArgument.ToString());
break;
case "From User Master":
Session["flag"] = "2";
Response.Redirect(e.CommandArgument.ToString());
break;
case "Subscriber Master":
Session["flag"] = "3";
Response.Redirect(e.CommandArgument.ToString());
break;
case "Import Susbcribers":
Session["flag"] = "4";
Response.Redirect(e.CommandArgument.ToString());
break;
default:
Session["flag"] = "0";
Response.Redirect(e.CommandArgument.ToString());
break;
}
}
}