I have the following script in my page:
window.onload = LoadElement;
function LoadElement() {
document.getElementsByTagName('asp:Panel');
};
function setPage(frame, page) {
document.getElementById('WindowShow').innerHTML = page;
}
At first I want the asp:Panel be read it onload. Continuing I'm calling the setPage Function in order to load a Page inside to this Panel...
But the debugger throws me the error `I can't load the porperty .innerHTML to a null reference value.
I see from the debugger that really the getElement has a value of null, but the value inside is not null.
Is someone to know what is going on here? I'm confused... very much...
ADDITIONAL INFORMATION'S
The sub to use in order to call the script is this:
Private Sub button1_Click(sender As Object, e As System.EventArgs) Handles button1.Click
Dim url As String = "/Pages/Support/Asp/Help01.aspx"
Dim urlURI As String = HttpContext.Current.Request.Url.AbsoluteUri
Dim urlPath As String = HttpContext.Current.Request.Url.AbsolutePath
Dim root_url As String = Strings.Left(urlURI, urlURI.Length - urlPath.Length)
Dim frameName As String = "WindowShow"
iPageLoad(frameName, sender, root_url + url)
End Sub
Public Sub iPageLoad(FrameId As String, sender As Object, msg As String)
Dim cstype As Type = Me.GetType()
Dim innerMess As String = msg
Dim url As String = HttpContext.Current.Request.Url.AbsoluteUri
Dim script As String = "setPage('" + FrameId + "', '" + innerMess + "')"
If Not Page.ClientScript.IsStartupScriptRegistered(Me.GetType(), "iPage") Then
Page.ClientScript.RegisterStartupScript(cstype, "iPage", script, True)
End If
End Sub
NEW SCRIPT
<td id="TD1" rowspan="9" runat="server">
<asp:Literal id="WindowShow" runat="server" Mode="PassThrough" />
<script type="text/javascript">
function setPage(page) {
document.getElementById('WindowShow');
}
</script>
</td>
With this script throw me the error ìnnerHTML is not a valid attribute for...` .
UPDATES
That is what my code has:
<table id="tbl" runat="server" class="maintable" >
<tr><td id="line1" class="tableline" runat="server">
<asp:Button ID="button1" runat="server" CssClass="tablebutton" Text="bla bla bla" />
</td>
<td id="TD1" rowspan="9" runat="server">
<asp:Literal id="WindowShow" runat="server" Mode="PassThrough" />
<script type="text/javascript">
function setPage(page) {
document.getElementById('WindowShow').innerHTML = page;
}
</script>
</td>
</tr>
</table>
And that is what is Server site look like:
<table id="MainContent_tbl" class="maintable">
<tr>
<td id="MainContent_line1" class="tableline">
<input type="submit" name="ctl00$MainContent$button1" value="bla bla bla" id="MainContent_button1" class="tablebutton" />
</td>
<td id="MainContent_TD1" rowspan="9">
'--------- It Shaw the TD1 but can't see the Literal element
<script type="text/javascript">
function setPage(page) {
document.getElementById('WindowShow').innerHTML = page;
}
</script>
</td>
</tr>
</table
Instead of asp:Panel use this:
window.onload = function () {
var panel;
panel = document.getElementById('<%=ServerSidePanel.ClientID %>');
// do something with panel
setPage(panel, "<span>Page inside panel.</span>");
};
function setPage(frame, page)
{
frame.innerHTML = page;
}
And in the code-behind expose the control in a property:
protected ServerSidePanel
{
get
{
return ... // the panel you want to get in JS
}
}
EDIT: server-side html injected panel
If you have the HTML on the server and want to have it inside the panel, there is no need to use JS at all. You can just assign it to a Literal instead of a Panel this way:
In the ASPX page:
<asp:Literal ID="injectionPoint" runat="server" CssClass="looks_like_a_panel" Mode="PassThrough" />
In the code behind (here in C#, sorry I don't speak VB):
string html;
// load somehow the html, here it is simply assigned
html = "<span>internal HTML</span>";
// assign html to literal
injectionPoint.Text = html;
That's all. No JS at all.
Here you can find a VB example doing pretty much the same, but without PassThrough mode:
Literal VB example on MSDN
Finally I found a solution to my issue which may close this question and probably opens another...
I use two scripts:
<script type="text/javascript">
window.onload = getTag()
function getTag() {
var td = document.getElementsByTagName('td');
return td;
}
</script>
<script type="text/javascript">
var myTD = getTag();
function setPage(page) {
// var ch = myTD.item(1).children[0];
//ch.value = page;
myTD.item(1).childNodes[1].innerHTML = '<iframe class="tablecolumndiv" src="' + page + '" />';
}
</script>
And my asp.net code:
<td id="TD1" rowspan="9" runat="server" class="tablecolumn">
<div id="WindowShow" runat="server" class="tablecolumndiv">
</div>
</td>
In the first script I call onload for the td element.
In the second I call the returned td from the first and passes dynamically the page I want thru an iFrame.
Now the question comes up is "Why I didn't do it from the asp.net code".
Well I did that but I was facing the problem to leave the iFrame when I finish my job.
So now... tomorrow... I'll try to close the dynamically opened iFrame and finish the all issue here...
Related
Good day!
I need a help on activating my javascript function via on-load on code behind.
Here is my code:
string script = #"var applyCss = function () {
var css = '#CalendarPanel1-month-day-20170607, #CalendarPanel1-month-day-20170614 {background-color: #D0D3D4;}';
Ext.net.ResourceMgr.registerCssClass('someCssClassId', css);
}; ";
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "css", script, true);
By the way, my code above works in front-end via button click.
But my desired result is, I want my javascript function to work on page load without needing to click the button. I put my javascript function in code-behind because I will put dynamic dates in the css variables. The code above still has static variables. (CalendarPanel1-month-day-20170607)
Will gladly appreaciate any response / solution. Big thanks!
You could use an immediately invoked function to do the trick. Basically you don't give a name to your javascript function and you invoke it right after it's defined.
For example:
var script = #"(function () {alert('Hello');})(); ";
ScriptManager.RegisterStartupScript(this, typeof(Page), "123", script, true);
You need to wrap the function with its body between parenthesis then another set of parenthesis to invoke the function.
You can also pass parameters to your function (which I'm assuming it's what you want to do):
var myAlertText = "Hello Hello";
var script = #"(function (myText) {alert(myText);})('" + myAlertText + "');" ;
If I were you though I would defined the function in client code and just invoke it from code behind with the right parameters.
An alternative and fancier way to call javascript code from code behind would be using X.Call(). Check out this example:
<%# Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (!X.IsAjaxRequest)
{
string script = #"var myJSSideVar = 'my var value';
var applyCss = function (paramOne, paramTwo) {
var css = '#CalendarPanel1-month-day-20170607, #CalendarPanel1-month-day-20170614 {background-color: #D0D3D4;}';
Ext.net.ResourceMgr.registerCssClass('someCssClassId', css);
Ext.Msg.alert('applyCss called.', 'I\'ve been run with parameters: (' + paramOne + ', ' + paramTwo + ').');
};";
var hi = "hello";
X.AddScript(script);
X.Call("applyCss", new object[] { hi, new JRawValue("myJSSideVar") });
}
}
</script>
<html>
<head runat="server">
<title></title>
</head>
<body>
<form runat="server" id="form1">
<div>
<ext:ResourceManager runat="server" />
</div>
</form>
</body>
</html>
Notice the second parameter sent to the script call is sent "raw", i.e., it calls: applyCss("hello", myJSSideVar)
If you need to pass but one single parameter you don't need to pass an array, e.g. X.Call("applyCss", hi);
I'm trying to pass a string and call a javascript function from the code behind in vb.net, once I click a button. The javascript is in a separate file.
Below is the code for the button:
/MyProject/myfile.aspx
<HTML>
...
...
<asp:textbox id="txtSearch" runat="server" Width="120px" CssClass="midField"></asp:textbox>
<input class="midBtn" id="btnSearch" type="button" value="Search" name="btnSearch" runat="server">
...
...
<script src='<%= Page.ResolveClientUrl("~/script/functions/myFunc.js")%>' ></script>
</HTML>
/MyProject/myfile.aspx.vb
Private Sub btnSearch_ServerClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.ServerClick
Dim searchString As String
searchString = txtSearch.Text
Dim rsname As String = Page.ResolveClientUrl("~/script/functions/myFunc.js")
Page.ClientScript.RegisterStartupScript(Me.GetType(), "mySearch", "mySearch('" & searchString & "')", True)
End Sub
/MyProject/script/functions/myFunc.js
function mySearch(searchString){
// ...
// logic for mySearch
// ...
}
I can't get the javascript function to be called and I need to reference the .js file at the end of my .apsx page. The error I get from the debugger is Uncaught ReferenceError: mySearch is not defined, please help.
If the criterion of choice is a dropdown, probably a better solution (I used jquery) is put the js file at the end of page, and check the dropdown value from javascrpit (here set as variable) and intercept the postback of .NET button:
<script type="text/javascript">
$(document).ready(function () {
var dropdown = 1;
$('.midBtn').click(function () {
if (dropdown == 1) {
mySearch($('.midField').val());
return false;
} else {
// ... postback
}
});
});
</script>
In this case you must be sure that the classes selector (midBtn and midField) are unique.
I'm trying to render a list of items from a database as a block of JSON so I can use it on the client side via JavaScript. I thought the best way to do this would be to use a Repeater or ListView to render my items, but I get a "server tag is not well formed" error.
This is my code
<asp:ListView runat="server" ID="rptAddresses" ItemPlaceholderID="plcItems">
<LayoutTemplate>
<script type="text/javascript">
var addressConfig = [
<asp:Placeholder ID="plcItems" runat="server"/>
];
</script>
</LayoutTemplate>
<ItemTemplate>
{
'id': '<asp:Literal runat="server" Text="<%# Eval("AddressID") %>" />',
'name':...
What am I doing wrong?
I'm not sure what you are doing wrong, but it is probably your literal. You can just do this instead:
'id': '<%# Eval("AddressID") %>'
That said there are other alternatives to sending an array to your script:
ClientScriptManager.RegisterArrayDeclaration is built into the framework. Here's an example taken from the linked page:
' Define the array name and values.
Dim arrName As String = "MyArray"
Dim arrValue As String = """1"", ""2"", ""text"""
' Get a ClientScriptManager reference from the Page class.
Dim cs As ClientScriptManager = Page.ClientScript
' Register the array with the Page class.
cs.RegisterArrayDeclaration(arrName, arrValue)
This will render the following array just before the close of your form:
var MyArray = new Array("1", "2", "text");
Personally, I prefer using the JavaScriptSerializer because you can freely serialize basically any object:
Protected Function GetArray() As String
Dim exampleList As New List(Of Pair) From {New Pair(7, 4), New Pair("Foo", "Bar")}
Dim serializer As New Script.Serialization.JavaScriptSerializer()
Return serializer.Serialize(exampleDictionay)
End Function
You can then add it to your .aspx file anywhere you like:
var myArray = <%=GetArray()%>;
which actually renders as an array literal:
var myArray = [{"First":7,"Second":4},{"First":"Foo","Second":"Bar"}];
Of course, you could also do it completely in your aspx markup:
<% Dim serializer As New Script.Serialization.JavaScriptSerializer() %>
var array = <%= serializer.Serialize({"look", "at", "this"})%>;
After much tweaking with all combination of single and double quotes, I eventually solved this by putting the <script> tag in a literal. ie:
<LayoutTemplate>
<asp:Literal runat="server" Text='<script type="text/javascript">' />
var macroConfig = [
<asp:Placeholder ID="plcItems" runat="server"/>
];
$(document).ready(function () {
...
});
<asp:Literal runat="server" Text='</script>' />
</LayoutTemplate>
It seems the parser gets confused with where the script tag ends and the server control tag starts.
In my Vb .net code-behind (Visual Studio 2005), in a method fired by click event:
hdnUrl and hdnParameters are hiddenFields
Protected Sub btnExample_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExample.Click
.
.
.
hdnUrl.Value = "Mypage.aspx?i=" & SomeCveDefinedInCodeBehind.Tostring & "&u=" & OtherCveDefinedInCodeBehind.Tostring
hdnParameters.value = "resizable: no; scroll: no; center: yes; dialogHeight: 525px; dialogWidth:750px; status: no;"
ScriptManager.RegisterClientScriptBlock(Page, Page.GetType, DateTime.Now.ToString, "<script type='text/javascript'> ShowWindow(); </script>", False)
.
.
.
In my page:
<asp:Content ID="Content3" ContentPlaceHolderID="cph3" runat="Server">
.
.
.
<asp:HiddenField ID="hdnUrl" runat="server" Value="" />
<asp:HiddenField ID="hdnParameters" runat="server" Value="" />
<asp:HiddenField ID="hdnResult" runat="server" Value="" />
<script language="javascript" type="text/javascript">
function ShowWindow()
{
alert('i am here');
var url = document.getElementById('<%= hdnUrl.ClientID %>').value;
var Parameters = document.getElementById('<%= hdnParameters.ClientID %>').value;
//For test:
alert(url); //------ i need to get here: "My page.aspx?...", but i always get: ""
alert(parameters); // i need to get here my parameters, but i always get: ""
.
.
.
var dialogWin = window.showModalDialog(url, "some text", parameters); //showModalDialog window, will return a data that i need in CodeBehind
document.getElementById('<%= hdnResult.ClientID %>').value=dialogWin.result;
//Then i could manage the result, in code-behind
}
</script>
</asp:Content>
Only if in the hidden field definition i set:
<asp:HiddenField ID="hdnUrl" runat="server" Value="My text" />
i can get this text in the javascript alert, but i need define the text in code-behind
Thanks for your Help and suggestions.
is there another way for pass url and parameters, to the window.showModalDialog???
or another way for get the result of the window.showModalDialog in code.behind???
Watch the casing on your Parameters variable. Also try using RegisterStartupScript instead of RegisterClientScriptBlock. The difference is the former will put your javascript at the bottom of the page while the latter puts it at the top. This will cause the script to run before the document it fully loaded.
ScriptManager.RegisterStartupScript(Page, Page.GetType, DateTime.Now.ToString, "<script type='text/javascript'> ShowWindow(); </script>", False)
I am using an external javascript file for my asp.net project. Now i want to get the session value in that javascript. How can i get the session value in that javascript file?
Thanks in advance..
<script>
var someSession = '<%= Session["SessionName"].ToString() %>';
alert(someSession)
</script>
This code you can write in Aspx. If you want this in some js.file, you have two ways:
Make aspx file which writes complete JS code, and set source of this file as Script src
Make handler, to process JS file as aspx.
You can access your session variable like '<%= Session["VariableName"]%>'
the text in single quotes will give session value.
1)
<script>
var session ='<%= Session["VariableName"]%>'
</script>
2) you can take a hidden field and assign value at server;
hiddenfield.value= session["xyz"].tostring();
//and in script you access the hiddenfield like
alert(document.getElementbyId("hiddenfield").value);
For me this code worked in JavaScript like a charm!
<%= session.getAttribute("variableName")%>
hope it helps...
I tried following with ASP.NET MVC 5, its works for me
var sessionData = "#Session["SessionName"]";
protected void Page_Load(object sender, EventArgs e)
{
Session["MyTest"] = "abcd";
String csname = "OnSubmitScript";
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the OnSubmit statement is already registered.
if (!cs.IsOnSubmitStatementRegistered(cstype, csname))
{
string cstext = " document.getElementById(\"TextBox1\").value = getMyvalSession() ; ";
cs.RegisterOnSubmitStatement(cstype, csname, cstext);
}
if (TextBox1.Text.Equals("")) { }
else {
Session["MyTest"] = TextBox1.Text;
}
}
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script language=javascript type="text/javascript">
function getMyvalSession() {
var txt = "efgh";
var ff = '<%=Session["MyTest"] %>' + txt;
return ff ;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack=true ></asp:TextBox>
<input type="submit" value="Submit" />
</div>
</form>
</body>
</html>
If you are using VB as code behind, you have to use bracket "()" instead of square bracket "[]".
Example for VB:
<script type="text/javascript">
var accesslevel = '<%= Session("accesslevel").ToString().ToLower() %>';
</script>
var sessionVal = '#Session["EnergyUnit"]';
alert(sessionVal);