Send a variable from vb.net to javascript - javascript

I have some problems when i send the value variable in visual basic net to javascript, for example: this code:
Partial Class borrador1 // The code in aspx
Inherits System.Web.UI.Page
public myVariable As string
public sub MyMethod()
myVariable ="Hello World"
end sub
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
MyMethod()
end sub
In the next part i try to recive the value in javascript
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<script type="text/javascript">
var variable = '<%= myVariable%>';
</script>
<body>
</html>
I load the page and i see the next problem in the browser:
[HttpException (0x80004005): Please, see whether wrapping the code block, generating the exception, within RadCodeBlock resolves the error.]
Telerik.Web.UI.RadAjaxControl.MoveUpdatePanel(Control initiator, Control updated) +437
Telerik.Web.UI.RadAjaxControl.PerformRender() +419
Telerik.Web.UI.RadAjaxControl.OnPageRender(HtmlTextWriter writer, Control page) +1450
Telerik.Web.UI.RadAjaxControl.RenderPageInAjaxMode(HtmlTextWriter writer, Control page) +197
System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +131
System.Web.UI.Page.Render(HtmlTextWriter writer) +40
System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +150
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5363
thanks for yours comments.

It seems that you need to register the script. Here is a link for your exact issue you are having. Happy coding!

Thanks my friend, but I resolve my problem. I use the controls telerik UI for ASP.NET AJAX, especific the charts, result the panel have a conflicts when i pass the variable, i comment the line (<%-- --%>) or write a function in jquery wait to load all the controls and when finish send the variable to javascript.

Related

How do I put javascript programmatically into <head> block?

I need to put some javascript absolutely in the <head> block of the page -- it must execute before the rest of the page because a possible outcome of the script is to redirect to a different page.
However, when I use RegisterClientScriptInclude (to put some jQuery in there) and RegisterClientScriptBlock for my code which uses the jQuery, it puts it near the top of the <body> block, and it does not execute. I can't see a way to programmatically put this javascript into the <head> block -- it must be programmatically because sometimes I don't want it there, and sometimes I do.
I've tried to see if I can directly reference Content1, the ID of the asp:Content element corresponding to the <head> block, but no go.
Just in case anyone thinks that RegisterStartupScript might work: it doesn't. It puts it lower in the <body> block than everything else. Oddly enough.
Want some code? Here:
Type csType = this.GetType();
ClientScriptManager clientScript = Page.ClientScript;
if (!clientScript.IsClientScriptIncludeRegistered(jqueryScriptName))
{
clientScript.RegisterClientScriptInclude(jqueryScriptName, "~/Scripts/jquery-1.7.1.min.js");
}
if (!clientScript.IsClientScriptBlockRegistered(citrixDetectorScriptName))
{
clientScript.RegisterClientScriptBlock(csType, citrixDetectorScriptName, citrixDetectorScriptText, true);
}
By popular demand, how I detect the ActiveX component. This is JScript.
try {
var icaObj = new ActiveXObject("Citrix.ICAClient");
var CitrixVersion = icaObj.ClientVersion.split(".");
var MajorMinorVersion = CitrixVersion[0] + "." + CitrixVersion[1];
if (MajorMinorVersion == "11.0") {
// Citrix is OK
}
else {
window.navigate("WrongCitrix.aspx?Citrix=" + MajorMinorVersion);
}
}
catch (e) {
window.navigate("NoCitrix.aspx");
}
If the ActiveX component is not present, then redirection is a page that tells the user they need to install it. If the ActiveX component is any other version than 11.0, then the redirect is to a page that explains this and how to deal with the situation (backrevving for example).
An prior check during page load checks to make sure they have Internet Explorer v4 thru v9, because any other version will not work with the product (and IE10+ will crash if it even tries to load v11.0 of the ActiveX component).
If I understand your question, you can insert PlaceHolder control wherever you want inside the page.
<%# Page Language="C#" AutoEventWireup="True"
CodeBehind="Default.aspx.cs" Inherits="WebApplicationTelerik.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script type="text/javascript"
src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<asp:PlaceHolder runat="server" ID="PlaceHolder1"></asp:PlaceHolder>
</head>
<body>
<form id="form1" runat="server">
</form>
</body>
</html>
protected void Page_Load(object sender, EventArgs e)
{
PlaceHolder1.Controls.Add(new LiteralControl(
"<script type=\"text/javascript\"> alert('here'); </script>"));
}
document.GetElementsByTagName("head")[0].appendChild( newScriptNode );
or jQuery
$("head")[0].append( newScriptNode );
If you really must insert JavaScript into the head tag, you can just make it an ASP.NET control and insert a control into it's child collection.
E.g. In the ASPX file:
<head runat="server" id="header">...</head>
In the code behind:
header.Controls.Add(new Literal("<script type='text/javascript'>...</script>"));
Although I do think you need to think about your process, it would be more efficient to redirect the user in the back-end before the page is rendered.
Oh and RegisterStartupScript correctly places your JavaScript after your html for increased load performance.

Jscolor stops working after first postback of fresh deploy, but continues to work after postback of a reload

Could anyone tell me something helpful to the following behavior in JSF with Jscolor component?
I have got this simple xhtml code:
<?xml version='1.0' encoding='UTF-8' ?>
<!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"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>RDFa test</title>
</h:head>
<h:body>
<script type="text/javascript" src="resources/js/jscolor/jscolor.js"/>
<h:form>
<h:commandButton class="color" value="ok"/>
<h:commandButton value="server" type="submit" action="#{testBean.tmp}"/>
</h:form>
</h:body>
</html>
TestBean.java:
#ManagedBean
#SessionScoped
public class TestBean implements Serializable {
public TestBean() {}
public void tmp() {
System.out.println("SERVER!");
}
}
If I do the first deployment and click on the "server" button, the Jscolor will go away and does not work (it is like destroying the javascript on the page)! If I then reload the page and click on the same button, the Jscolor works normally. There's no exception in server log, nor any error in Firebug JS console. How is this caused and how can I solve it?
EDIT:
I am not the only developer, who straggles with this issue. Here tyhand describes exactly, what I mean: http://www.tek-tips.com/viewthread.cfm?qid=1641380
COuld you please explain me what is happening and how to solve it?
Finally I found a solution. It is so easy!!! I have to add before all input fields with class='color' (binding fileds to the jscolor) this code:
<script>jscolor.init();</script>
I wanted to use jscolor inside a repeater that was inside an update panel in a custom DNN module.
None of the various solutions I saw here worked...I finally figured it out.
At top of HTML in your usercontrol:
Use <dnn:DNNJsInclude..... /> to point to your jscolor.js file, then add
<script type="text/javascript">
function pageLoad(sender, args) {
$(".jscolor").each(function (i, obj) {
var picker = new jscolor(obj);
});
};

Call a function defined in an external javascript function from vb.net code behind (.html not .aspx)

I have a plain .html page which has a hiddenField and a reference to External.js. Since I am implementing using ASP.NET, server side will execute first. However, I need to execute a function in External.js before server code execution. The solution is available by the having the following code:
*In .aspx *
<script src="External.js" type="text/javascript"></script>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />`
In .aspx.vb
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
If Not Page.IsPostBack Then
ScriptManager.RegisterStartupScript(Me, Me.GetType(), "register", "MyFunction();", True)
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
The code works perfectly when I am using a .aspx page. Obviously, I cannot use any ASP.NET server controls in a plain .html page. So using <asp:ScriptManager> in a .html page will not work. How can I do the same exact thing but in an .html page. What should be defined in the .html page and how can I call the function from the code behind, keeping in mind that I cannot use any <asp:> controls.
Ok so what I am trying to do is that I have my External.js which has the function populateHidden() which basically sets a value to my hiddenField.
function populateHidden()
{
document.getElementByID('Hidden').value = "abcdefg";
}
I also have another function PassData() which basically initializes an ajax request to the server to pass the value of Hidden to the code behind (using a webMethod). The problem is that I want populateHidden() to execute first so that passData() passes abcdefg (after populateHidden() is executed) to the code behind to store the value in a database. So currently the way I am running both functions is as follows.
in .html
<body onload="PassData()">
in code-behind
trying to execute populateHidden(); on Page_Load since server side executes first.
I borrowed this from #Cleydson's answer:
JS
function MyFunction()
{
populateHidden();
PassData();
}
HTML
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="External.js" type="text/javascript"></script>
</head>
<body onload="MyFunction();">
...
</body>
Now you're calling populateHidden() before PassData()
I’m not sure if I understood it correctly. But, if you want do call a script in the same way you’ve done you just need to do it:
<body onload="MyFunction();">
complete version:
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="External.js" type="text/javascript"></script>
</head>
<body onload="MyFunction();">
...
</body>
</html>
Is it?

Google Docs Viewer gives javascript error inside ASP.Net page

I'm trying to embed google docs viewer in my page.
Here's the test.aspx code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="test.aspx.cs" Inherits="Web_Application.test" %>
<!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>
</head>
<body>
<iframe id="documentLoader" src="https://docs.google.com/viewer?embedded=true&url=http://view.samurajdata.se/license.pdf"
style="width:100%; height:800px;">
</iframe>
</body>
</html>
Here's my test.aspx.cs
namespace Web_Application
{
public partial class test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
I get errors such as
'Line: 409
Error: Unable to get value of the property 'k': object is null or undefined'
or
'Line: 458
Error: Unable to get value of the property 'a': object is null or undefined'
which are from google doc viewer online javascript resource...
So I embedded the script in the header and it worked. But the problem is, if I do this in a user control or in a page inherited from a master page I get those errors again.
How can I solve this?
Thank you.
try this iframe script independent of any browser or version this will work ....
<iframe id="documentLoader" src="https://docs.google.com/viewer?url=http://view.samurajdata.se/license.pdf&chrome=true" style="width: 100%; height: 800px;">
</iframe>
mark yes if works !!! :)
<iframe id="documentLoader"
src="https://docs.google.com/viewer?url=http//view.samurajdata.se/license.pdf&embedded=true"
style="width:100%; height:800px;">

How to call javascript function from code-behind

I wrote a javascript with a asp.net page.
In Asp.net Page
<HTML> <HEAD>
<script type="text/javascript">
function Myfunction(){
document.getElementId('MyText').value="hi";
}
</script>
</HEAD> <BODY>
<input type="text" id="MyText" runat="server" /> </BODY>
In Code-behind
Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Me.Load
If Session("My")= "Hi" Then
I want to call "Myfunction" javascript function
End If
End Sub
How can I do?
One way of doing it is to use the ClientScriptManager:
Page.ClientScript.RegisterStartupScript(
GetType(),
"MyKey",
"Myfunction();",
true);
This is a way to invoke one or more JavaScript methods from the code behind.
By using Script Manager we can call the methods in sequence. Consider the below code for example.
ScriptManager.RegisterStartupScript(this, typeof(Page), "UpdateMsg",
"$(document).ready(function(){EnableControls();
alert('Overrides successfully Updated.');
DisableControls();});",
true);
In this first method EnableControls() is invoked.
Next the alert will be displayed.
Next the DisableControls() method will be invoked.
There is a very simple way in which you can do this. It involves injecting a javascript code to a label control from code behind. here is sample code:
<head runat="server">
<title>Calling javascript function from code behind example</title>
<script type="text/javascript">
function showDialogue() {
alert("this dialogue has been invoked through codebehind.");
}
</script>
</head>
..........
lblJavaScript.Text = "<script type='text/javascript'>showDialogue();</script>";
Check out the full code here: http://softmate-technologies.com/javascript-from-CodeBehind.htm (dead)
Link from Internet Archive: https://web.archive.org/web/20120608053720/http://softmate-technologies.com/javascript-from-CodeBehind.htm
If the order of the execution is not important and you need both some javascript AND some codebehind to be fired on an asp element, heres what you can do.
What you can take away from my example:
I have a div covering the ASP control that I want both javascript and codebehind to be ran from. The div's onClick method AND the calendar's OnSelectionChanged event both get fired this way.
In this example, i am using an ASP Calendar control, and im controlling it from both javascript and codebehind:
Front end code:
<div onclick="showHideModal();">
<asp:Calendar
OnSelectionChanged="DatepickerDateChange" ID="DatepickerCalendar" runat="server"
BorderWidth="1px" DayNameFormat="Shortest" Font-Names="Verdana"
Font-Size="8pt" ShowGridLines="true" BackColor="#B8C9E1" BorderColor="#003E51" Width="100%">
<OtherMonthDayStyle ForeColor="#6C5D34"> </OtherMonthDayStyle>
<DayHeaderStyle ForeColor="black" BackColor="#D19000"> </DayHeaderStyle>
<TitleStyle BackColor="#B8C9E1" ForeColor="Black"> </TitleStyle>
<DayStyle BackColor="White"> </DayStyle>
<SelectedDayStyle BackColor="#003E51" Font-Bold="True"> </SelectedDayStyle>
</asp:Calendar>
</div>
Codebehind:
protected void DatepickerDateChange(object sender, EventArgs e)
{
if (toFromPicked.Value == "MainContent_fromDate")
{
fromDate.Text = DatepickerCalendar.SelectedDate.ToShortDateString();
}
else
{
toDate.Text = DatepickerCalendar.SelectedDate.ToShortDateString();
}
}
asp:run javascript method
Add this line to the bottom of the page before </form> tag, at least under the js function you wrote.
the reason of doning this is avoid calling your method before your
browse knowing what is the funcion and finally do nothing.
<% Response.Write($"<script>yourfunction('{Config.id}');</script>"); %>
ps: I've tried all methods up there but nothing worked fine for me. And I figure out this easy and wonder way of calling js method on my own!

Categories

Resources