Load javascript code after loading code behind - c#

I have a web site released at facebook platform, i am using C# .Net 2008, the problem is that i am loading an array elements from code behind in javascript arary and i am loading elelment element using the following javascript code :
ArList = new Array('<%=ListOfWords[0]%>','<%=ListOfWords[1]%>','<%=ListOfWords[2]%>','<%=ListOfWords[2]%>');
the problem that when i call an element from the array as follows :
document.getElementById("WordDiv").innerHTML = ArList [0];
The element is not set with the value inspite the array in the code behind has values and i don't know why the value of the array element is not set ? and in some cases i found it loaded with value and everything go right so may be it's a problem in rendering so the value of code behind is not seen in client side ? or where is the problem come ?
and when i traced the application in IE i found the status bar report a javascript error then disappered and say done and when the yellow allert appears in the status bar i have clicked it and noticed the message says : object expected.
The problem now is that in onload event of the body tag i call a function in the javascript that intialize the javascript array with values from code behind array and the problem is that in some cases the function is not entered as i traced it by putting an alert in the begining of the function and i found that when the javascript array is not filled the code of the function is not entered as the alert is not showed so i don't know how to force the DOM to enter this function which i call it in the tag here sample of the code:
javascript code:
<!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">
</head>
<body onload="IntializeArr(); return false;">
<form id="form1" runat="server" >
..........Some Controls...............
</form>
<script type="text/javascript" language="javascript">
var TList;
var BList;
function IntializeArr()
{
TList = new Array('<%=ListofT[0]%>','<%=ListofT[1]%>','<%=ListofT[2]%>','<%=ListofT[3]%>','<%=ListofT[4]%>','<%=ListofT[5]%>','<%=ListofT[6]%>','<%=ListofT[7]%>','<%=ListofT[8]%>','<%=ListofT[9]%>');
BList = new Array('<%=ListOfB[0]%>','<%=ListOfB[1]%>','<%=ListOfB[2]%>','<%=ListOfB[3]%>','<%=ListOfB[4]%>','<%=ListOfB[5]%>','<%=ListOfB[6]%>','<%=ListOfB[7]%>','<%=ListOfB[8]%>','<%=ListOfB[9]%>');
}
</script>
</body>
</html>
C# Code :
public string[] ListOfB = new string[15];
public string[] ListofT = new string[15];
And the code behind array is filled from data returned from database and they are filled i have traced them and each time and they are filled and i found that the problem from javascript i don't know if it is from facebook platform or from my code but i think that it is not from my code as the problem that i call a function in the onload of the tag and the function is not entered and this is the problem so can any one help me please
Hope that i will find a solution as i got depressed

If the IntializeArr() function is not being called, it is most likely a javascript error in the page, and most likely caused by some invalid javascript characters in the ListofT or ListofB arrays.
You should be escaping any single quotes or newlines.
Easiest way to check is to just "view source" in the browser once the page has loaded. Look down to your script and find what values were put it and you should see if there were any errors.

Maybe ListofWords[0] contains an apostrophe?

Are you outputting the JS array creation to the page inside <script> tags?
You have to emit that javascript so that the browser can run it - then ArList will be available on the page to other javascript.

Agree, more code example is needed.
Usually I solve something like this by using Sys.Application.add_init() or $(document).ready(). However there are other possible solutions. Use an AJAX request to get the array. Or something like:
function setInnerHtml() {
if (typeof(ArList) != "undefined") {
document.getElementById("WordDiv").innerHTML = ArList[0];
} else {
setTimeout("setInnerHtml()", 40);
}
}

Related

Displaying html links in a different order on page load

I have a bunch of static links currently within a div, however Im after changing the order of the links on page load.
I've considered using a literal and a loop through the links in code behind but im stumped. Maybe a repeater... I need a push in the right direction please!
Im fairly new to this so any help would be much appreciated. Thanks
(c# or vb.Net)
ok so lets say that you would store the links in a Links.txt file because there could be hundreds of links for example..
1. Create the .txt file
2. Make note of the file location.
3. Save the file with the links in them
4. use this code in your project to load the links
List<string> strUrlLinks = new List<string>(File.ReadAllLines(FilePath + FileName.txt));
in code you can then hover over strUrlLinks and you will see the Links
to access the individual links do it based on it's [Index] position
I know you asked for an answer in c# or vb.net and may have some technical restraints on this, but to create this functionality in jQuery is almost trivial considering the links are already hardcoded on the page.
See the example below which sorts in descending order on the link text.
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<div id="linksContainer">
Line 1
Line 3
Line 2
</div>
<script type='text/javascript'>
$(window).load(function(){
var orderDivLinks = function(desc) {
$('div#linksContainer').children().detach().sort(function(a,b) {
var compA = $(a).text();
var compB = $(b).text();
return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
}).appendTo(document.body);
}
orderDivLinks(0);
});
</script>
</body>
</html>

How to pass data from SQL Server to jQuery var [Flot]

I have two columns of data in an Database on MS SQL Server. One is datetime variable and another is an int.
Im trying jQuery and Flot to plot the datetime vs int.
I can programatically get the data from SQL Server using C#. But how do I pass it to the JavaScript File which has the vars for flot?
If you want to call a script in a loaded html document, you can use the Invoke method from the appropriate HtmlDocument or WebBrowser object to call a javascript function within that page, for example:
http://msdn.microsoft.com/en-us/library/system.windows.controls.webbrowser.invokescript.aspx
I am unsure how you would pass the data from c# to a *.js file in your case, I dont think its possible. But you could try a hack on the page that contains the *.js include you could try declaring and setting the javascript variable to the c# code (so in the ASPX, if its ASP.NET) and then putting the *.js include reference after that point and in it not re-declaring the variable but using it. You can also use JSON or AJAX to call server side code and return values and execute code.
Scenario 1: (The hack way, which is not clean and hard to maintain but does the job)
File.aspx
<script language="javascript" type="text/javascript">
var MyVariable = "<%=C_Variable_On_Code_Behind%>";
</script>
<script type="text/javascript" src="/scripts/YourJsFile.js" >
</script>
YourJsFile.js
if(MyVariable != null && MyVariable.length > 0){
//Do some thing.
}
Scenario 2: (JSON, AJAX, JQUERY UI)
jquery ui sample for a autocomplete: try this link
Another example: Or this link
Scenario 3: (Writing to the client from server-side c#)
Use RegisterStartupScript or RegisterClientScriptBlock via the ClientScriptManager object, here is a dummy code I put together so you can look them up and have an idea so you can find out more, this is not meant to be full code.
ClientScriptManager script = Page.ClientScript;
if (!script.IsClientScriptBlockRegistered(this.GetType(), "YourLabelForThis"))
{
script.RegisterClientScriptBlock(this.Page.GetType(), "YourLabelForThis",
"<script type=\"text/javascript\">var MyVariable = "Dummy text";</script>", false);
}
Please note you have to place the js code as an include or further code in the right position in the page whther you want it before or after this code, so lookup RegisterStartupScript or RegisterClientScriptBlock via the ClientScriptManager. To see where your code will be placed and how you should handle it. Also look at the page source in your browser to also see it.

dynamic Javascript in asp.net

well. The problem i'm facing is i have my own custom control and i do a query , get records and dynamically add html controls to the page based on the data.
Now there's the problem of adding some dynamic javascript
I do this with the help of literal controls.
<asp:Literal runat="server" ID="latEventToolTipJqueryScripts"></asp:Literal>
This works like a charm
<script language="javascript" type="text/javascript">
// <![CDATA[
Sys.Application.add_load(WireEvents_<%=this.ID%>); // fix wiring for .NET ajax updatepanel
$(WireEvents_<%=this.ID%>); // handle page load wiring
function WireEvents_<%=this.ID%>() {
<asp:Literal runat="server" ID="latEventToolTipJqueryScripts"></asp:Literal>
}
// ]]>
</script>
I add the literal text dynamically from code behind.
However, when placing the control in an updatepanel, the postbacks don't update the script.
EDIT: The Sys.Application.add_load rewires the necessary functions just fine with the updatepanel. The problem is that the script that needs to be in place of the literal, doesn't update when in an updatepanel.
I've tried the ClientScript.RegisterStartupScript but it has the same effect as with the literal control trick. Any help?
---------------------------SOLVED (tnx to Pranay Rana)----------------------------------
Got rid of the literal in the ascx side. as well as the Sys.Application.add_load
now it's only in the code behind. The thing that was throwing me off was the JQuery thing.
this.strBuilderJS.Append( "<script language='javascript' type='text/javascript'>" +
"$(WireEvents_" + this.ID + ");" +
"function WireEvents_" + this.ID + "(){"+
" alert('stuff');");
this.strBuilderJS.Append( "}</script>");
and then
ScriptManager.RegisterStartupScript(this, this.GetType(), "strBuilderJS", strBuilderJS.ToString(), false);
Make use of ScriptManager.RegisterStartupScript() to register your script...may resolve problem ...
Check this resolve your problem : Add JavaScript programmatically using RegisterStartupScript during an Asynchronous postback
I would recommend on a different approach. To create a dynamic javascript for any language. I would create a reference to a dynamic file. For this example I will use .NET
Create a test.aspx page and add this script:
<script type="text/javscript" src="js/foo.aspx"></script>
Make sure your page response with the right content type. So for this instance I would add this on page load code behind for your foo.aspx:
Response.ContentType = "application/javascript";
On the foo.aspx html view add your javascript code.
alert("<%=DateTime.Now%>");
Browse your test.aspx page and you should see an alert with the current date
You should be able to move forward from here. The goal is to separate the javascript file from the static page.
Happy Coding.
How to change text of ASP Button control on anchor tag click
We have an ASP Button below and we want to change text when WE click on anchor tag
<asp:Button ID="btn_Add" runat="server" CssClass="button2" onclick="btn_Add_Click"/>
We have following two anchor tags
Add New
Add New
Now we add following code in script tag
<script type="text/javascript" language="javascript">
function changeText1() {
document.getElementById("lbl_header").innerText = 'Add New Teacher';
document.getElementById("btn_Add").value = 'Add';
}
</script>
<script type="text/javascript" language="javascript">
function changeText2() {
document.getElementById("lbl_header").innerText = 'Delete Teacher';
document.getElementById("btn_Add").value = 'Delete';
}
</script>

asp.net accessing javascript variables after ajax updatepanel

I'm using AJAX on an ASP.NET web project to update a page. Some of my functions return XML that I want to embed on the page after it reloads. This part works, here's a sample of how it looks at the top of the page:
var productXML = "<?xml version=\"1.0\"?><ArrayOfProduct xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><Product><ActualProdID>123</ActualProdID><Name>Test</Name><Description>Test</Description><Edition>Test</Edition><Platform>Test</Platform><Family>Test</Family><Type>Test</Type><DeploymentTypes>Test</DeploymentTypes><BaseActualProdID>Test</BaseActualProdID><Price>0</Price></Product></ArrayOfProduct>";
Later in the page I'm trying to use the XML but it's not working. I tried to do something simple and just throw an alert box in that looks like this:
<script type="text/javascript">
function closeLoading()
{
jQuery('.pleaseWaitPanel').css({ 'display': 'none', 'visibility': 'hidden' });
alert("here");
alert(productXML);
alert("here2");
}
</script>
closeLoading() is called inside:
window.onload = function () { Sys.WebForms.PageRequestManager.getInstance().add_endRequest(closeLoading); };
It loads the jQuery and the first alert "here" works perfect. When I go to alert the productXML, nothing happens. It doesn't throw a JavaScript error, I'm using Firebug. I can confirm the XML is on the page.
Any help on this would be GREATLY appreciated!!
From your code snippets, it looks like your closeLoading function is only being called in your window.onload function. This means that it won't be called after any Ajax request completes as the window won't be reloaded.
I would try moving your call to Sys.WebForms.PageRequestManager.getInstance().add_endRequest(closeLoading) to just before your closing server-side form tag:
<form runat="server">
...
<script>
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(closeLoading);
</script>
</form>
Hope this helps.
var productXML
Is a ServerSide variable, so you don't have access to this in Client script.
If you want to use in a javascript function you can do this :
1) Put the result in a textbox hidden, like
<input type='hidden' value='<%=productXML%>'>
then simply get the value of the textbox.

Reading C# property into JQuery code

I'm trying to read the value of a C# property from my code behind file into some JQuery script (see below). The JQuery selector I've written accesses an ASP.Net GridView and then a CheckBox field within the gridview. Whenever a checkbox is checked or un-checked the code is hit, but I need to access the C# property from the code behind to take the appropriate action based on the value of the property.
$(".AspNet-GridView-Normal > td > input").click(function() {
//Need to access the C# property here
//Take action here based on the value of the C# property
});
This may be stating the obvious, but the code behind doesn't exist on the client side where your jQuery code is executing. What you could do is assign the value of the property to a hidden field on the server side so that when you need to check it with jQuery on the client side it will be available. So you might do the following on the client side.
Markup:
<asp:HiddenField ID="hfValueINeedToKnow" runat="server"/>
Code Behind:
hfValueINeedToKnow.Value = <some value>;
jQuery:
$("#<%= hfValueINeedToKnow.ClientID %>").val();
You might need to make some minor changes to support a value for each row of the grid, but hopefully this explains the general idea.
You mentioned in a comment that the value is an int. And I see it's also a public property in your codebehind. This is trivial now - you don't need to escape the value, nor access it in some round-about way, and you get type safety for free:
<script>
$(".AspNet-GridView-Normal > td > input").click(function() {
var AvailableInstalls = <%= AvailableInstalls %>;
});
</script>
Well you can't.
You need to render the C# property in some element (perhaps a hidden field) and then look at it that way.
But explain further: What property are you trying to check?
What I've done for this scenario in the past is to print out my code value into the markup and store whatever it is in a javascript variable, thus making a copy of it available to client-side code. This is a silly example, but hopefully it makes sense:
<%
var messsge = "Hello World!"
%>
<html>
<head>
<script type="text/javascript">
function ShowMessage()
{
var msg = '<%= message %>';
if(msg)
alert(msg);
}
</script>
</head>
</html>
There isn't a really clean way to do this. Your best bet would probably be to use the ClientScript.RegisterClientScriptBlock functionality built into ASP.NET. Here's a good primer.
private int myValue;
protected void Page_Load(object sender, EventArgs e) {
ClientScript.RegisterClientScriptBlock(typeof(Page),
"vars", "<script>var myParams = { p1: " + myValue + ", p2: 'My Name' };</script>");
}
This will put the supplied script on your page towards the top of the form. You can change that too. Obviously, it isn't the prettiest; you are essentially string concatenating a different language, but it will work, and for simple variable declaration isn't too rough on the eyes.
ASP Embedded in JavaScript always makes me nervous from the perspective of script injection attacks and the inability to unit-test your JavaScript.
This build upon an ealier answer:
<script type="text/javascript">
$(".AspNet-GridView-Normal > td > input").click(function() {
var AvailableInstalls = $("#MyHidden").val();
});
</script>
You could move it to a hidden variable:
<input type="hidden" id="#MyHidden" value="<%= AvailableInstalls %>" />
However this doesn't get around the problem of injection. So you could you could add a server-side hidden variable and set it from the Page_Load event function in ASP.NET.
(P.s. you also need the attribute type="text/javascript" in your script tag to make it valid HTML).
If you will put your value into an asp:HiddenField with id hfValueINeedToKnow, the simplest way to retrieve this value client side is
var jsvar = $("[id$=hfValueINeedToKnow]").val();
So you can also place this code in a separate .js file.

Categories

Resources