How can I populate an unordered list for the jQuery treeview from SQL query?
I'm totally new in ASP.NET so I think it's an easy question I have. In my application I try to use jQuery treeview, in Default page I have the following code:
<script src="jquery-1.6.2.js" type="text/javascript"></script>
<script src="jquery.treeview.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#example").treeview({
persist: "location",
collapsed: true,
animated: "medium"
});
});
</script>
I need to populate the tree, and so I use the following example:
<ul id="example" runat="server" class="filetree">
<li><span class="folder">Folder 1</span>
<ul>
<li><span class="file">Item 1.1</span></li>
</ul>
</li>
<li><span class="folder">Folder 2</span>
<ul>
<li><span class="folder">Subfolder 2.1</span>
<ul>
<li><span class="file">File 2.1.1</span></li>
<li><span class="file">File 2.1.2</span></li>
</ul>
</li>
<li><span class="file">File 2.2</span></li>
</ul>
</li>
<li class="closed"><span class="folder">Folder 3 (closed at start)</span>
开发者_高级运维 <ul>
<li><span class="file">File 3.1</span></li>
</ul>
</li>
<li><span class="file">File 4</span></li>
</ul>
Problem is I get the data for the treeview from my database by using an SQL query.
So my question is how do I populate this unordered list with my data? Thanks a lot in advance!
EDIT: This is a way to pass your strongly typed object to your view.
Create a method to load your list and add it to your Session so you can call this method on every postback to make sure your list remains in Session, like so:
private void LoadMyListToSession()
{
DataContext ctx = New DataContext(); // instantiate your datacontext if you haven't done so before
List<Object> ObjectList = ctx.MyDataTable().ToList(); // load your list
Page.Session.Add("MyVariableName", ObjectList); // add your list to the session
}
Execute a similar code on your page_load event or any other method you want to make sure your list remains in Session, like so:
private void Page_Load(object sender, System.EventArgs e) {
LoadMyListToSession();
}
Pass your View a strongly typed object, such as a List of the class you use to store the items in your database and iterate through it to create your <ul>
dynamically.
For example, consider ObjectList to be your strongly typed List:
<% List<Object> ObjectList = (List<Object>) Session["ObjectList"]; &>
<% if(ObjectList != null && ObjectList.Count > 0){ %>
<ul>
<% foreach(Object item in ObjectList)
{ %>
<li><%= item.Name; %></li>
<% } %>
</ul>
<% } %>
As you can see in the example above, if ObjectList is a List of items that you load from the database, you can iterate through it and in each iteration create a <li>
with whatever property from the item of your iteration you desire.
Remember that you need to load your object from the Session as shown above!
If you still got questions, please ask.
精彩评论