I've got code like this in an .aspx file:
<script type="text/javascript" language="javascript">
function init()
{
<%= x %>
}
It works fine (x is a string that will be bound to some JavaScript at runtime), but when compiling I get an "Expected expression" warning on the <%=
I know it's not the nicest code in the world, but there are various historical bits of code that like to inject little bits of JavaScript into the page. All perfectly innocent :)
The warning is happening because the code block is inside a JavaScript <script> block; the compiler is trying to be smart about recognizing the difference between HTML/controls and JavaScript.
Although it's a bit ugly, you should be able to eliminate the warning by using eval('<%= x %>')
You might also have a look at an article I wrote on using ASP.NET to create dynamic JavaScript: http://www.12titans.net/p/dynamic-javascript.aspx
If you wanted to be perfectly legal, use a literal:
<asp:Literal ID="litX" runat="server"></asp:Literal>
and set its Text to the whole <script type="text/javascript" language="javascript">...</script> block on the server side.
Visual Studio is validating the HTML markup on the page. Strictly speaking, the '<' is not valid XHTML. This warning may be caused by a limitation of the validation as Visual Studio is interpreting the '<' character inside javascript as meaning 'less than'!
Obviously these inline expressions are not valid client code. One can change the HTML validation options in Tools|Options|Text Editor|HTML. Mind you, it may be better to simply ignore these warnings rather validate against HTML 4.01 or turn off the validation completely.
If all you're doing is adding javascript to your page, you could use RegisterClientScriptBlock to build the script server-side and then let it output it to the page.
This way you don't have to have any server-side scripting within your page and all the overhead that goes with that.
I've done this before and not had problems. However, I use jQuery's $(document).ready() instead of init(). I don't think that should be an issue, though.
What datatype is x? If it is a string, try wrapping it in single quotes, and if it's a number use the parse function for that datatype.
<script type="text/javascript" language="javascript">
var s;
var n;
function init()
{
s = '<%= x %>';
n = parseInt('<%= x %>');
eval('<%= x %>'); /* Raw Javascript */
}
</script>
Another issue would be the access level of the property. ASP.NET web forms can't access private fields directly from the code-behind. Access has to be protected or public.
Eval Javascript Function
I found the problem that I was having with this.
It seems I had incorrectly commented out HTML above the script.
<%-- <div id="directionpanel" ></div>--%>
<script type="text/javascript">
var LIST = <%= getJson()%>;
</script>
I was getting the expected expression warning on getJson()
Correctly commenting the HTML will fix the warning.
-->
Related
I need to print a DataViewGrid from a website made in ASP.NET and have am using JavaScript to do it as it seems much easier that achieving it is C#. Below is the code that I am using to try and print the document.
<script type="text/javascript">
function doPrint() {
var prtContent = document.getElementById('<%# dgvInvoices.ClientID %>');
prtContent.border = 0;
var WinPrint = window.open('', '', 'left=100,top=100,width=1000,height=1000,toolbar=0,scrollbars=1,status=0,resizable=1');
WinPrint.document.write(prtContent.outerHTML);
WinPrint.document.close();
WinPrint.focus();
WinPrint.print();
WinPrint.close();
}
I had to change line 3 from ('<%= dgvInvoices.ClientID %>'); because it was giving me a control error, and now I believe this is stopping my document from printing. Does anyone have any work around or fixes for this? Or an easy way to print in C#?
The original error was:
The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
If you are using ASP.NET Ajax and have a ScriptManager in your page or master page, you could do:
var prtContent = $get('<%= this.dgvInvoices.ClientID %>');
Also, if you are using the .Net framework version 4 or above, you can set the property ClientIDMode="Static" in the control, so the ClientID will be rendered as declared and you'll be able to use the document.getElementById javascript function passing the declared ID as parameter.
I want to be able to send data to Javascript in a div like this:
<div class="dontDisplay><%= myData %></div>
However, the challenge is that the HTML will get messed up. There seems to be a plethora of encoding and decoding schemes out there, but I can't find a javascript/C# pair that are guaranteed to be compatible for all possible inputs (including Unicode.)
Does anyone know of a pair that are known to be perfectly compatible?
Thanks
You most probably want to use json. You can embed a string in your page that creates a local variable on your page using json inside a script-tag:
<script> var myJsonVariabe = { propertyNane: "value" }; </script>
You can serialize a .net object to json using the DataContractJsonSerializer.
You appear to be just putting some text into HTML text content, for which the correct approach is plain old HTML-encoding:
<div class="dontDisplay"><%= Server.HTMLEncode(myData) %></div>
or in ASP.NET 4.0:
<div class="dontDisplay"><%: myData %></div>
If JavaScript needs to extract this, you can use DOM methods:
<div id="foo"><%= Server.HTMLEncode(myData) %></div>
<script type="text/javascript">
var myData= document.getElementById('foo').firstChild.data;
</script>
although this assumes that there's exactly one text node in there, and will break if myData is an empty string. You can work around this by having a getTextContent method that checks all the childNodes for being text nodes and adds their data together, or use textContent with fallback to innerText for IE, or use a library to do it (eg. text() in jQuery).
alternatively you can put the data in an attribute:
<div id="foo" title="<%= Server.HTMLEncode(myData) %>">...</div>
<script type="text/javascript">
var myData= document.getElementById('foo').title;
</script>
if there is a suitable attribute available (title might not be appropriate), or a comment, or directly into a JavaScript variable using JSON as suggested by Rune.
I'm having problems using JQuery inside an ASP.Net User Control I've created a sample and here is the markup for my user control:
<%# Control Language="C#" ClassName="UC" AutoEventWireup="true"
CodeFile="UC.ascx.cs" Inherits="UserControls_UC" %>
<span id="Licenses"></span>
<script type="text/javascript">
$(document).ready(function() {
var ctlID = $("span[id$='Licenses']");
ctlID.text = "Testing";
});
</script>
If I include this script tag <script type="text/javascript" src="js/jquery-1.3.2.js" /> in the aspx file containing the user control to reference JQuery, nothing happens. If I don't include it, I get a JavaScript error dialog saying there was a runtime error and that an Object was expected. Any ideas what I may be doing wrong?
text is a function in jQuery. Try:
ctlID.text("Testing");
Prefixing the '$' to the id gets all elements that ends with "Licenses" .
Make a quick change to test this to '#' will get you exactly one element.
$(document).ready(function() {
var ctlID = $("#Licenses");
ctlID.text = "Testing";
});
To make it work with attribute selector try
$('span[#id=Licenses]') // You can omit the # in the latest version of jquery.
I think you should use something like this:
var ctlID = $("span[id$='Licenses']").get(0);
ctlID.text = "Testing";
Have you included the jquery library correctly on master page?
Is that not meant to be dollar before id, i.e. $id='Licenses' ? or even a #
How can I detect server-side (c#, asp.net mvc) if the loaded page is within a iframe? Thanks
This is not possible, however.
<iframe src="mypage?iframe=yes"></iframe>
and then check serverside if the querystring contains iframe=yes
or with the Referer header send by the browser.
Use the following Code inside the form:
<asp:HiddenField ID="hfIsInIframe" runat="server" />
<script type="text/javascript">
var isInIFrame = (self != top);
$('#<%= hfIsInIframe.ClientID %>').val(isInIFrame);
</script>
Then you can check easily if it's an iFrame in the code-behind:
bool bIsInIFrame = (hfIsInIframe.Value == "true");
Tested and worked for me.
Edit: Please note that you require jQuery to run my code above. To run it without jQuery just use some code like the following (untested) code to set the value of the hidden field:
document.getElementById('<%= hfIsInIframe.ClientID %>').value = isInIFrame;
Edit 2: This only works when the page was loaded once. If someone have idea's to improve this, let me know. In my case I luckily only need the value after an postback.
There is no way of checking this that will fit your requirement of "secure" as stated in your comment on #WTP's answer.
I don't think the server-side can do this, so why not put a hidden control in your page that will be in the iframe? When the URL in the iframe loads, you can add some client-side code to set the hidden input to indicate you are in an iframe. The easiest check would be on the client-side in an onload method, like this:
// Set hidden input
someHiddenInput.value = self != top
It's more secure than the querystring, but it still might not be enough security for you.
My 2 cents.
Old question but why not a more simplistic approach like
var isFramed = self !== parent
I'm currently trying to register a JS function call from a .NET page which simply calls a small function on the .aspx page that will close the window.
The RegisterClientScriptBlock code is like this:
Page.ClientScript.RegisterClientScriptBlock (typeof(Page), "closeBox", "<script type='text/javascript'>closeBox();</script>");
This sort of thing works elsewhere in the application on different pages. However, in this case I get a runtime JS error: Error: Expected '/' and when I debug, sure enough the inserted javascript is:
<script type='text/javascript'>closeBox();<
As you can see, it hasn't added the /script> for some reason! I've tried to leave out the tags myself and used:
Page.ClientScript.RegisterClientScriptBlock (typeof(Page), "closeBox", "closeBox();", true);
but with the same results.
I've also tried RegisterStartupScript to no avail.
Has anyone else come across this before? Any ideas on what's causing it and on how to fix it?
I'm unsure if it's exactly the same (my memory not being what it once was) but I think I've hit a similar problem in the past. The solution was to put some line terminators between the various parts of the script, i.e.
Page.ClientScript.RegisterClientScriptBlock (typeof(Page), "closeBox", "<script type='text/javascript'>\n\rcloseBox();\n\r</script>");
Where was this RegisterClientScriptBlock? Was it in a <script runat="server"> element?
If so, the aspx parser will see the </script> inside your C# string literal as being the end of the enclosing script element and will stop there. If you want to put the sequence </script> inside a <script> (and this goes for normal JavaScript too) you must escape it to break up the sequence. A good way is:
"\x3C/script"
The error turned out to be something completely unrelated.