Treeview control in ASP .net - javascript

I have a treeview control in my web application. I build this tree view dynamically.
Is there anyway to select a node and change the color of the selected node using javascript or any other method running in client side(i mean without post back).
i am using c# and asp.net to bulid my application

EDIT (To explain a little more on JQuery):
JQuery is a .js file containing JavaScript functions to make it easier to navigate a document, select DOM elements, create animations, handle events, and develop Ajax applications.
You can download JQuery.js file from JQuery official website, then reference to the JQuery.js file (like you reference to other .js file) before you call your first JQuery script, as followed:
<script type="text/javascript" src="jQuery.js"></script>
Or alternatively, you can use the JQuery.js file hosted by Google. This is what I did for my testing. Below is the complete code of my .aspx page:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="TreeView.aspx.cs" Inherits="TreeView" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript"
src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
// You may specify partial version numbers, such as "1" or "1.3",
// with the same result. Doing so will automatically load the
// latest version matching that partial revision pattern
// (e.g. 1.3 would load 1.3.2 today and 1 would load 1.4.2).
google.load("jquery", "1.4.2");
google.setOnLoadCallback(function() {
// Place init code here instead of $(document).ready()
//change cursor to hand when user mouseover tree nodes
$(".TreeView1_0").mouseover(function() {
$(this).css('cursor', 'pointer');
});
//unbold all nodes then bold the selected node to indicate it's selected
$(".TreeView1_0").click(function() {
$(".TreeView1_0").css('font-weight', 'normal');
$(this).css('font-weight', 'bold');
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TreeView ID="TreeView1" runat="server">
</asp:TreeView>
</div>
</form>
</body>
</html>

2 ways I can thought of to implement this:
Wrap your treeview with Ajax UpdatePanel. This is more straight forward.
Remove hyperlink from tree nodes using recursive function, then bind client side click event to all the nodes using JQuery.
More details for method 2 as followed..
Place treeview control onto aspx page
<asp:TreeView ID="TreeView1" runat="server">
</asp:TreeView>
Add dummy nodes and call recursive function to remove hyperlinks
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//add dummy nodes
TreeView1.Nodes.Add(new TreeNode() { Value = "1", Text = "One" });
TreeView1.Nodes.Add(new TreeNode() { Value = "2", Text = "Two" });
TreeView1.Nodes.Add(new TreeNode() { Value = "3", Text = "Three" });
//call recursive function to remove hyperlinks
RemoveHyperLinks(TreeView1, TreeView1.Nodes);
}
}
Implement the recursive function
System.Web.UI.WebControls.TreeView RemoveHyperLinks(System.Web.UI.WebControls.TreeView treeView, TreeNodeCollection treeNodes)
{
foreach (TreeNode node in treeNodes)
{
node.SelectAction = TreeNodeSelectAction.None;//here the link is removed
if (node.ChildNodes != null && node.ChildNodes.Count > 0)
{
treeView = RemoveHyperLinks(treeView, node.ChildNodes);
}
}
return treeView;
}
Place this JQuery code on aspx page
//change cursor to hand when user mouseover tree nodes
$(".TreeView1_0").mouseover(function() {
$(this).css('cursor', 'pointer');
});
//unbold all nodes then bold the selected node to indicate it's selected
$(".TreeView1_0").click(function() {
$(".TreeView1_0").css('font-weight', 'normal');
$(this).css('font-weight', 'bold');
});

Related

How to give dynamic query parameter in <script> src?

I am building a simple asp.net application and in my aspx page I want to reference a script with dynamic query parameter.
For example:
<script src="../javascript/script.js?v=#var#" type="text/javascript"></script>
In the above code script path can have different query parameter in place of #var#.
I have also tried following code to get the parameter value from code behind.
<script src="../javascript/script.js?v=<%# myVar %>" type="text/javascript"></script>
but, here <%# myVar %> returns blank value. If I use = instead of # then it works perfectly if I add the script reference at the bottom of the page.
But, it only works if I reference the script at the bottom of page. otherwise it will throw the error.
"The Controls collection cannot be modified because the control contains code blocks (i.e. `<%= %>`)."
Now, my question is, "Is there any other way to do the same?"
I am assuming you are using ASP.net not MVC. I have tried this with ASP.net and done this by code behind approach you can create your script tag by code behind like below:
protected void Page_Load(object sender, EventArgs e) {
string jScriptValidator;
jScriptValidator = "<script type='text/javascript' src='../javascript/script.js?v=#123'></script>"; // your dynamic script tag with dynamic parameter
Page.RegisterStartupScript("key", jScriptValidator);
}
and result is follows:
Hope it helps you.

auto invoke a javascript function from the child view, after jquery ready, in _layout view, when page loads

strong textIn my ASP MVC 5 app, I have a (master - Jquery loads here) _layout.cshtml and (child, my function sortable here, not loading) views tableView.cshtml
In the child tableView.cshtml, I've written custom JS functions that need to be invoked on Jquery Read $ ready. Since jquery has already loaded in the master page, how can I attach my function (and 3rd parts plugins) invoke it when my child page loads?
if possible, please share a modular way to attach and initialize my functions and 3rd party plugins in the childviews on the child view loading/navigation load, so that when the main jquery function loads, it also invokes my functions.
_layout.cshtml
// DOM ready is completed in master layout, I have custom JS plugin/code (sortable)
// in the child view that I need to load, when that loads
$( document ).ready(function() {
console.log( "Master layout ready, done" );
});
TableView.cshtml
// in my tableView, that inherits layout from master,
// how can I get this loaded when the page loads
(function() {
console.log( "How can I get child table plugin, loaded!" );
})();
You should make use of #RenderSection() which act as placeholders to render content from the view
You layout page might look something like
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
.....
// Include common style sheets here
#RenderSection("styles", false) // placeholder for styles
#Scripts.Render("~/bundles/modernizr")
</head>
<body>
....
#RenderBody()
....
// Include all common scripts here
#Scripts.Render("~/bundles/jquery") // include jquery first
#RenderSection("scripts", required: false) // placeholder for page specific scripts
</body>
</html>
and in the view
#model YourModel
// html here
....
#section styles {
<link href="~/Content/PageSpecificStyleSheet.css" rel="stylesheet" />
}
#section scripts {
// Add page specific scripts and plugin files here
#Scripts.Render("~/bundles/jqueryval")
<script src="../../Scripts/MyScript.js" type="text/javascript"></script>
....
<script type="text/javascript">
// Other javascript code here
</script>
}
Note #RenderSection("styles", false) is in the <head> element and #RenderSection("scripts", required: false) is immediately before the closing </body> tag meaning any scripts defined in the view will be loaded after the page elements have loaded (and after the jquery file)

Loading content into tooltip via ajax

I am using this Plugin to load content into tooltip via ajax. It is pretty simple to understand and start using it.
This is my jsp page in which I want to load content dynamically into tool tip on hovering on a link.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<html>
<head>
<script src="jquery.js" type="text/javascript"></script>
<script src="jquery.hoverIntent.js" type="text/javascript"></script> <!-- optional -->
<script src="jquery.cluetip.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('a.basic').cluetip();
});
function web()
{
alert('asffdsr');
}
</script>
</head>
<table border="1">
<tr>
<th>Question name</th>
<th>Group ID</th>
<th>opt1(#votes)</th>
<th>opt2(#votes)</th>
<th>opt3(#votes)</th>
<th>opt4(#votes)</th>
<tr>
<c:forEach var="questions" items="${questionslist}">
<tr>
<td><a class="basic" href="http://www.google.com" rel="http://www.google.com" ><c:out value="${questions.question}"/></a></td>
....
If you look into the above code, at the bottom you will find the <a> tag with class = basic and the page to be loaded into the tooltip via ajax is http://www.google.com
In the head you can see the script src and the javascript functions. I have imported the all the js files into the folder containing the jsp page.
But for some reason the tooltip is not appearing. What is wrong here and how to correct it? And also is there any way of checking if all the 3 js files jave been imported into the page?
The following structure describes where the css and the jsp files are present. The css and js fields are present inside the web content folder and the jsp files are present in
WEB CONTENT
WEB-INF
JSP FILES..
CLUETIP CSS AND JAVASCRIPTFILES..
This is the screenshot. As you can see the js fields are not being loaded. But the css files are being retrieved.
EDIT#1
The page is loaded via ajax inside a div. So on clicking view page source, we cannot see the the source code of the stuff inside the div.
EDIT#2
The jquery.js file is not being imported even when using CDN i.e in the network tab of the developer tool, there is no call made for the the javascript file. I have given the script src line in the head section.
EDIT: Based on the edits to the question here is what is going on. When you load content on a page via Ajax, any script tags in that content will not be executed. See this question: Loading script tags via AJAX for more details. Be sure to read all the answers, as the solution may be dependent on your particular scenario.
Original Answer
You're trying to do an ajax request from your site to another domain, google.com. This is not allowed by browsers, its called a cross domain request. According the the qtip error handler:
error: function(xhr, textStatus) {
if ( options.ajaxCache && !caches[cacheKey] ) {
caches[cacheKey] = {status: 'error', textStatus: textStatus, xhr: xhr};
}
if (isActive) {
if (optionError) {
optionError.call(link, xhr, textStatus, $cluetip, $cluetipInner);
} else {
$cluetipInner.html('<i>sorry, the contents could not be loaded</i>');
}
}
}
you should be getting the following: <i>sorry, the contents could not be loaded</i> loaded into your tooltip (see jsfiddle). Check the error console, the most obvious answer is that you are getting a 404 error on one of your files, which should show up in the developer tools of whatever application you are using. See what happens in this fiddle where I replace 'cluetip' with a non existant javascript file. The chrome developer console looks like this:

Externalize JavaScript for Views

I've an ASP.NET MVC application with inline JavaScript that only applies to specific views.
If I put all the JavaScript on main Layout page, I get error message as not ID exists on all pages.
Is there a way to externalize the JavaScript for each view?
Here is one way. This is using razor view engine
In you layout page between the head tags create a section
<head>
#RenderSection("Head", required: false);
</head>
then in your view create a section and put your script tags in it.
#section Head
{
<script type="text/javascript">
do some java script...
</script>
}
You could also reference external libraries that are specific to that page, like a light box or something.
If you are using MVC 2 you can use a content placeholder.
// this goes in your master page in your head tag
<asp:ContentPlaceHolder id="Script" runat="server"/>
// this goes in your view -- not partial
<asp:Content ID="Content1" ContentPlaceHolderID="script" runat="server">
<script type="text/javascript" src="foo.js"></script>
</asp:Content>
In MVC 3 you can do this.
I use a HtmlHelper extension to register my used scripts on each controller-action and the "MasterPage" renders each registered script with the correct script tag.
HtmlHelper:
public static void RegisterScript(string path)
{
if (!HttpContext.Current.Items.Contains("RegisteredScripts"))
HttpContext.Current.Items.Add("RegisteredScripts", ";" + path);
else
HttpContext.Current.Items["RegisteredScripts"] = ";" + path;
}
public static MvcHtmlString RegisteredScripts(this HtmlHelper html)
{
var lines = new StringBuilder();
if (html.ViewContext.HttpContext.Items.Contains("RegisteredScripts"))
{
foreach (var k in html.ViewContext.HttpContext.Items["RegisteredScripts"].ToString().Substring(1).Split(';'))
{
lines.Append(html.Script(k));
}
}
return MvcHtmlString.Create(lines.ToString());
}
// Helper-functions
public static MvcHtmlString Script(this HtmlHelper html, string path)
{
if (!ExistsInContext(html, path))
{
return Render(html, "<script type=\"text/javascript\" src=\"{0}\"></script>", path);
}
return MvcHtmlString.Create("");
}
private static bool ExistsInContext(HtmlHelper html, string path)
{
return html.ViewContext.HttpContext.Items.Contains(path);
}
In the controller-action just call:
Helpers.HtmlHelpers.RegisterScript("~/Scripts/custom.js");
Hope this helps
The javascript could test if 'ID' is null or undefined, and not fire the code if it is.

Dynamic (2 levels) Javascript/CSS Loading IE6

i am trying to dynamically include js (and css) files into a webpage like this:
index.html -> loader_a.js -> a_foo.js, a_bar.js, a_foo.css and so on.
While this works without a problem in FF (using appendChild) i cant get it to run in IE6.
I've tried various available solutions (adding to dom node, ajax call and eval and more from (http://ntt.cc/2008/02/10/4-ways-to-dynamically-load-external-javascriptwith-source.html) here and there and others like post #2013676) but it's not doing what its supposed to do.
When i check with DebugBar i see that my include files (eg a_foo.js) is actually loaded, but its content is empty - on other included files (1 Level/directly) this content is show so i assume there is the problem ...
The "error" i get is alway undefined object which is o/c b/c the function i call is not loaded properly so not much of a help. I dont get any errors on the includes.
I've validated the javascripts so those whould be ok.
Does anyone have the ultimate solution for this?
I can recreate my tests and post some code if it helps.
Thanks,
regards,
Thomas
Sample HTML:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<HTML lang=en><HEAD><TITLE>Test</TITLE>
<script type="text/javascript" src="mmtest_files/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="mmtest_files/multiload.js"></script>
<script type="text/javascript" >
function init2() {
// using the data from the loaded js files
var a= mmf("a");
document.getElementById('status').innerHTML = "Variable set:" + a;
}
// magic...
include(['mmt.js'],init2);
</script>
<BODY >
<H2>Test me!</H2>
<SPAN id=status>status old</SPAN>
</BODY></HTML>
JS 1 is multiload from answer 1
JS2 is a test include:
function mmf(param)
{
return "Called with" + param;
}
You need to use document.write in ie, in order to load scripts in parallel.
See: Loading Scripts Without Blocking
I have such a script btw: Loading Multiple Javascript Files In Order Asynchronously
(it may need some enchancements in Chrome)
UPDATE
There is a callback function, it is optional. It can be used to couple dependent script to the files. EG:
function myjQueryCode() {
// ...
}
include(['jquery.js','jquery-ui.js'], myjQueryCode);
So that your jquery dependent code will run after the files has been loaded.

Categories

Resources