Server Controls Inside a JavaScript Block - javascript

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.

Related

Why Webmethod not firing when using ajax

I have a User Control (with Two TextBox and a label) Behind the code of the User Control On Prerender I Use RegisterStartupScript to call a JS function which calls a External JS function Which it calls a WebMethod. Everything works fine until calling the Webmethod. When calling the webmethod using AJAX. The web method does not fires up. I have no idea why. Any help would be appreciated.
SpecificExperienceControl.ascx
<%# Control Language="vb" AutoEventWireup="false" CodeBehind="SpecificExperienceControl.ascx.vb" Inherits="TardyAbsenteeReport.SpecificExperienceControl" %>
<asp:HiddenField ID="hdnID" runat="server" />
<div class="SpecExp">
<asp:TextBox ID="TextBox1" runat="server" CssClass="SpecExp-txtEmpID" ></asp:TextBox>
<asp:Label ID="Label1" runat="server" Text="Label" CssClass="SpecExp-txtLbl"></asp:Label>
<asp:TextBox ID="TextBox2" runat="server" CssClass="SpecExp-txtAcode"></asp:TextBox>
</div>
SpecificExperienceControl.ascx.vb
Public Class SpecificExperienceControl
Inherits System.Web.UI.UserControl
Dim number As Int16 = 0
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Public Property Value As String
Get
Return hdnID.UniqueID
End Get
Set(value As String)
hdnID.Value = value
End Set
End Property
'This function sends the necessary javascript to the page
Protected Sub Me_PreRender(sender As Object, e As EventArgs) Handles Me.PreRender
Dim cs = Page.ClientScript
Dim myType = Me.GetType()
'gets one total copy of JQuery
If Not cs.IsClientScriptBlockRegistered(myType, "jquery") Then
cs.RegisterClientScriptBlock(myType, "jquery", GetJQueryInclude())
End If
'gets one total copy of the toggle function in SpecificExp.js
If Not cs.IsClientScriptIncludeRegistered(myType, "helper") Then
cs.RegisterClientScriptInclude(myType, "helper", VirtualPathUtility.ToAbsolute("~/SpecificExperienceControl.js"))
End If
'gets one copy for each user control on the page of the js in the getStartupScript function below
cs.RegisterStartupScript(myType, "regEvents" & Value, getStartupScript(), True)
End Sub
Private Function getStartupScript() As String
Return "$(function(){$('#" & TextBox1.ClientID & "').change(function(){toggle('" &
TextBox1.ClientID & "','" & Label1.ClientID & "','" & TextBox2.ClientID & "')})});"
End Function
'This function get jquery include string
Public Function GetJQueryInclude() As String
Const CurrentJQueryVersion = "2.1.1"
Const formatString = "<!--[if {0}><script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/jquery/{1}/jquery.min.js'></script><!{2}[endif]-->"
Return String.Format(formatString, "lte IE 8]", "1.11.1", String.Empty) &
String.Format(formatString, "gt IE 8]", CurrentJQueryVersion, String.Empty) &
String.Format(formatString, "!IE]>--", CurrentJQueryVersion, "--<!")
End Function
End Class
SpecificExperience.aspx
<%# Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/Site.Master" CodeBehind="SpecificExperience.aspx.vb" Inherits="TardyAbsenteeReport.SpecificExperience" %>
<%# Register Src="~/SpecificExperienceControl.ascx" TagName="SpecExp" TagPrefix="HR" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<hr:SpecExp runat="server"></hr:SpecExp>
</ItemTemplate>
</asp:Repeater>
</asp:Content>
SpecificExperience.aspx.vb (Here I just bind the Repeater to a XML file that generates 25 empty rows)
Public Class SpecificExperience
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim xmldatasource2 As XmlDataSource = New XmlDataSource With
{.DataFile = "/App_Data/EmptyRows.xml"}
Repeater1.DataSource = xmldatasource2
Repeater1.DataBind()
End Sub
End Class
SpecificExperienceControl.js
function toggle(txtId, lblname, txtcode) {
$.ajax({
type: "POST",
url: "SearchEmpId.asmx/GetEmployeeName",
data: '{id: "it works"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$('#' + lblname).val(data.d);
}
});
}
SearchEmpId.asmx.vb Everything works as it supposed to and then this does not get fired up
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel
Imports Newtonsoft.Json
<System.Web.Script.Services.ScriptService()> _
<System.Web.Services.WebService(Namespace:="http://tempuri.org/")> _
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ToolboxItem(False)> _
Public Class SearchEmpId
Inherits System.Web.Services.WebService
<WebMethod()>
Public Shared Function GetEmployeeName(ByVal id As String) As String
Return "itworks"
End Function
End Class
Below is a screen shot of what I'm getting when the request is placed
When I click in Response Body I am seeing this. Why is it not finding the web method ?

getElementById returns null reference

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...

Changing HiddenField value in codebehind no changing in Javascript function in order to use showModalDialog

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)

How to put data from a database into javascript array from asp.net/vb.net

I am trying to make a simple program to put data from a database into a javascript array and then display one result in a textbox. Here is what I have so far
Dim cmd As New IfxCommand("select first 20 fname from table", conn)
Dim reader As IfxDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
Dim i As Integer = 0
While reader.Read()
ClientScript.RegisterArrayDeclaration("Names", "'" & reader("fname") & "'")
i += 1
End While
Dim cs As StringBuilder = New StringBuilder()
cs.Append("<script type=""text/javascript\""> function DoIt() {")
cs.Append("var TheTextBox = document.getElementById(""TextBox1"");")
cs.Append("TheTextBox.value = Names[0];")
cs.Append("script>")
TextBox1.Text = cs.ToString
Here is the asp
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<p>
<asp:Button ID="Button1" runat="server" Text="Button" onclick = "DoIt"/>
</p>
</form>
</body>
</html>
I am not sure what else I am supposed to do with this.
So you want to display the first name of your selected 20 in the TextBox initially and maybe lazy-load the other from client side via javascript?
Try this:
Using cmd = New IfxCommand("select first 20 fname from table", conn)
Dim tbl = New DataTable
Using reader = cmd.ExecuteReader()
tbl.Load(reader)
If tbl.Rows.Count <> 0 Then
Dim allNames = From row In tbl
Select row.Field(Of String)("fname")
TextBox1.Text = allNames.First
' embed names with quotes and separate the strings by comma '
Dim embeddedNames = From name In allNames Select String.Format("'{0}'", name)
ClientScript.RegisterArrayDeclaration("Names", String.Join(",", embeddedNames))
End If
End Using
End Using
Now you only need to implement the javascript function that switches the names if necessary. You can use String split then:
var allNames = documentGetElementById("Names").value.split(",");

Getting session value in javascript

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);

Categories

Resources