<%@ Page Language="C#" AutoEventWireup="true" CodeFile="JqueryMenu.aspx.cs" Inherits="JqueryMenu" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="1.11.1.min.js"></script>
<link href="jquery-ui.css" rel="stylesheet" />
<script src="jquery-ui.js"></script>
<link href="jquery-ui.structure.css" rel="stylesheet" />
<link href="jquery-ui.theme.css" rel="stylesheet" />
<script>
$(function () {
$.ajax({
url: 'Handler.ashx',
method: 'post',
dataType: 'json',
success: function (data) {
buildMenu($('#menu'), data);
$('#menu').menu();
function
buildMenu(parent, items) {
$.each(items, function () {
var li = $('<li>' + this.Menutext + '</li>')
li.appendTo(parent);
if (this.List && this.List.length > 0) {
var ul = $('<ul></ul>');
ul.appendTo(li);
buildMenu(ul, this.List);
}
})
}
}
});
});
</script>
<style>
.ui-menu {
width: 150px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<ul id="menu">
</ul>
</div>
</form>
</body>
</html>
Handler
public void ProcessRequest(HttpContext context)
{
string cs =
System.Configuration.ConfigurationManager.ConnectionStrings["mycon"].ConnectionString;
System.Collections.Generic.List<Menu> listmenu = new System.Collections.Generic.List<Menu>();
using (System.Data.SqlClient.SqlConnection
con = new
System.Data.SqlClient.SqlConnection(cs))
{
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("spmenudata",
con);
cmd.CommandType =
System.Data.CommandType.StoredProcedure;
con.Open();
System.Data.SqlClient.SqlDataReader
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Menu menu = new Menu();
menu.id = Convert.ToInt32(rdr["id"]);
menu.Menutext =
rdr["Menutext"].ToString();
menu.parentid =
rdr["parentid"] != DBNull.Value ? Convert.ToInt32(rdr["parentid"]) : (int?)null;
listmenu.Add(menu);
}
System.Collections.Generic.List<Menu> objlist = GetMenuTree(listmenu, null);
System.Web.Script.Serialization.JavaScriptSerializer js
= new
System.Web.Script.Serialization.JavaScriptSerializer();
HttpContext.Current.Response.Write(js.Serialize(objlist));
}
}
private System.Collections.Generic.List<Menu>
GetMenuTree(System.Collections.Generic.List<Menu> list, int? parentid)
{
return list.Where(x
=> x.parentid == parentid).Select(x => new Menu()
{
id = x.id,
Menutext = x.Menutext,
parentid = x.parentid,
List =
GetMenuTree(list, x.id)
}).ToList();
}

No comments:
Post a Comment