Printing in Javascript whilst using <%# %> - c#

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.

Related

JQuery in Sharepoint 2010

I'm writing web-part for Sharepoint 2010 and I need use JQuery.
$(function(){
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
clockImage = new Image();
setInterval(drawScene, 1000);
});
But when I try to debug my web-part, there is error:
Runtime error Microsoft JScript: The value of the "$" or is NULL, or if it is not defined or not an object Function
I've added JQuery to Style Library and my ascx page:
<script type="text/javascript" src="~/StyleLibrary/scripts/jquery.js"></script>
What should I do to fix it?
Look for the another reference avalialble for the Jquery in your page or the master page ?
If yes then remove one of the references..
If there are more then one reference calls available for the jquery script it will break the functionality of jquery script.
Also check for any other call tho jquery script before the reference is called ?
Thanks

Calling Javascript function from Code behind page

I have a script that I want to pop a window after 5 page views. The java script works fine on the default.aspx page with a link to call it. But I want to launce it from my default.aspx.cs page after my session var count gets to 5. How can I do this? Is it possible?
default.aspx
<script type="text/javascript">
window.name = "Register";
function popWin(link) {
var w = window.open(link.href, link.target, 'width=500,height=600,resizable');
return w ? false : true; // if popup blocker, use the default behaviour of the link
}
</script>
Default.aspx.cs page
if (Session["PagesViewed"].ToString() == "5")
{
//Call my Javascript function How?????
}
You can output javascript into a LiteralControl from your code behind:
.aspx:
<asp:Literal id="myLiteral" runat="server" />
Code behind:
myLiteral.Text = "<script type='text/javascript'>popWin('url');</script>";
When rendered this way, the output script will call the function - make sure it is lower in the page than where the function was defined to ensure it exists.
In ASP.Net you can do the following:
Page.ClientScript.RegisterStartupScript(
this.GetType(),
"openpopup",
"popWin('www.someurl.com');",
True);
If you need more control over your scripts placement #Oded has a better approach - as trying to call a function that has not been defined isn't a good idea...
You cannot call javascript functions directly from C#. However, what you could do is pass a <script> to the browser that executes the function.
response.Write("<script>popWin(something);</script>");

"Expected expression" with <%=foo%> inside JavaScript in .aspx file

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

JQuery in ASP.Net User Control in C#

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 #

Ajax Control Toolkit HTML Editor Customization Problem?

How to Change default setting for ACT HTML Editor? I want to load editor with for example Selected Bold Button or with rtl direction instead of ltr defaultly.
How can I perform that?
I overrided FillTopToolbar() method to add Custom buttons but I dont Know how to change default settings. as Default ltr is selected I want to change it to rtl.
I edited my answer to correct some things
The HTMLEditor doesn't provide a way to set the state of those buttons using serverside code. Although, on the client, it initializes by using Sys.Application.load Event. If you ran your code after their initializers, but before the user will interact with the UI, you could then set whatever properties you want to set in that event handler.
Here is the code you need to set the bold button and the rtl buttons states. You can take it from here if you want to change the states of other buttons:
// Attach a handler to the load event.
Sys.Application.add_load(myOnLoadLoader);
function myOnLoadLoader() {
//This will run JUST after ALL code that was set to run during the load event has run
window.setTimeout(myOnLoad, 0);
}
function myOnLoad() {
var editor = $find('<% =editor.ClientID %>');
var toolbar = editor.get_changingToolbar();
var toolbarButtons = toolbar.get_buttons();
for (var i = 0; i < toolbarButtons.length; i++) {
var toolbarButton = toolbarButtons[i];
if (toolbarButton instanceof AjaxControlToolkit.HTMLEditor.ToolbarButton.Rtl ||
toolbarButton instanceof AjaxControlToolkit.HTMLEditor.ToolbarButton.Bold) {
toolbarButton.set_activeEditPanel(editor.get_editPanel());
toolbarButton.callMethod();
}
}
}
Sys (and therefore Sys.Application) is a namespace that comes from the ASP.Net AJAX javascript (file(s) that are added thanks to the ScriptManager that you add to your page). If you use this, you need to be sure that this line Sys.Application.add_load(myOnLoad); runs after the ASP.Net AJAX files load. You can do this a couple of ways:
Add this script lower in the page than the scriptManager.
Move your script into a separate JS file, and use the ScriptManager to load it (recommended).
If you move your script into a separate file, you'll notice that var editor = $find('<% =youreditor.ClientID %>'); no longer works. That is because javascript files do not parse out server tags and replace them with the server side value (as aspx pages do). So the part that is a problem here is <% =youreditor.ClientID %>.
To fix that, here is what you do:
Add this to your aspx markup (in the head section):
<script language="javascript">
var myEditorId = '<%= youreditor.ClientID %>';
</script>
So it looks something like this:
<head runat="server">
<script language="javascript">
var myEditorId = '<%= youreditor.ClientID %>';
</script>
<title></title>
</head>
(If you are using a Master Page, you'll just add the script tag below the ScriptManager in your page)
And in your JS file, replace this
var editor = $find('<% =youreditor.ClientID %>');
with this
var editor = $find(myEditorId);
You will need to do this using CSS as the editor control doesn't support rtl natively. The following CSS will set direction to rtl -
div
{
direction:rtl;
}
The default styles for the HTML editor can be found in the Editor.css file.

Categories