I have a javascript function as shown below that is working. Note - i did change the line (from the internet examples)
WinPrint.document.write(printContent.innerHTML);
to
WinPrint.document.write(printContent.outerHTML);
i dont think i am supposed to do that but with innerhtml the grid wasnt formatted at all but with the value outerhtml it was fine...
So to summarize
why cant i use innerhtml like all the examples show - must be a bug
in my code somewhere
thanks,
Damo
Javascript
<script type="text/javascript">
function PrintGridData(GridToPrint) {
var printContent = document.getElementById(GridToPrint);
var windowUrl = 'about:blank';
var UserLoggedIn = $("#lblUser").text()
var now = new Date();
var strDateTime = [[AddZero(now.getDate()), AddZero(now.getMonth() + 1), now.getFullYear()].join("/"), [AddZero(now.getHours()), AddZero(now.getMinutes())].join(":"), now.getHours() >= 12 ? "PM" : "AM"].join(" ");
var windowName = 'Report';
var AuditPrintDetail = 'Report ' + UserLoggedIn + " " + strDateTime;
var WinPrint = window.open(windowUrl, windowName, 'left=300,top=300,right=500,bottom=500,width=1000,height=500');
WinPrint.document.write('<' + 'html' + '><head><link href="cssreference" rel="stylesheet" type="text/css" /><link href="assets/css/Main.css" rel="stylesheet" type="text/css" /> <title>' + AuditPrintDetail + '</title> </head><' + 'body style="background:none !important"' + '>');
WinPrint.document.write(printContent.outerHTML);
WinPrint.document.write('<' + '/body' + '><' + '/html' + '>');
WinPrint.document.close();
WinPrint.focus();
WinPrint.print();
WinPrint.close();
}
function AddZero(num) {
return (num >= 0 && num < 10) ? "0" + num : num + "";
}
function printItn() {
//you can put your contentID which is you want to print.
var printContent = document.getElementById('<%= pnlForm.ClientID %>');
var windowUrl = 'about:blank';
var uniqueName = new Date();
var windowName = 'Print' + uniqueName.getTime();
// you should add all css refrence for your Gridview. something like.
var WinPrint= window.open(windowUrl,windowName,'left=300,top=300,right=500,bottom=500,width=1000,height=500');WinPrint.document.write('<'+'html'+'><head><link href="cssreference" rel="stylesheet" type="text/css" /><link href="gridviewcssrefrence" rel="stylesheet" type="text/css" /></head><'+'body style="background:none !important"'+'>');
WinPrint.document.write(printContent.innerHTML);
WinPrint.document.write('<'+'/body'+'><'+'/html'+'>');
WinPrint.document.close();
WinPrint.focus();
WinPrint.print();
WinPrint.close();
}
reference it from here... click to view discussion.
and also see complete example with sample code javascript to print gridview data from client-side.
Related
I want to show some live random data on client using SignalR.
Problem Is whenever I refresh the page it creates one more connection
and shows multiple data.
Mostly I think my approach is wrong.
So what I have done.
Step 1: Installed SignalR Using Nuget Install-Package Microsoft.AspNet.SignalR
Step 2: Made changes in Startup.cs File as follows.
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
app.MapSignalR(); //Added this line for SignalR
}
}
Step 3: Created Hub Class. "ServerStatisticsHub.cs"
public class ServerStatisticsHub : Hub
{
public void ServerParameter()
{
Random r = new Random();
int p = 0;
int m = 0;
int s = 0;
while(true) //May be this is the foolish thing I'm doing
{
p = r.Next(0, 100);
m = r.Next(0, 100);
s = r.Next(0, 100);
Clients.All.broadcastServerStatistics("{\"processor\":" + p + ", \"memory\":" + m + ", \"storage\":" + s + "}");
System.Threading.Thread.Sleep(2000);
}
}
}
Step 4: Created an View in Home "ServerState.cshtml".
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<title>TestSignalR</title>
</head>
<body>
<div id="serverProcessor"></div>
<div id="serverMemory"></div>
<div id="serverStorage"></div>
<script src="#Url.Content("~/Scripts/jquery-2.2.3.min.js")"></script>
<script src="#Url.Content("~/Scripts/jquery.signalR-2.2.1.min.js")"></script>
<script src="#Url.Content("~/signalr/hubs")"></script>
<script>
$(function () {
// Reference the auto-generated proxy for the hub.
var serverStatistics = $.connection.serverStatisticsHub;
// Create a function that the hub can call back to display messages.
serverStatistics.client.broadcastServerStatistics = function (serverStat) {
var serverStatistic = JSON.parse(serverStat);
console.log(serverStatistic);
$('#serverProcessor').html(serverStatistic.processor + "%");
$('#serverMemory').html(serverStatistic.memory + "%");
$('#serverStorage').html(serverStatistic.storage + "%");
};
// Start the connection.
$.connection.hub.start().done(function () {
serverStatistics.server.serverParameter();
});
});
</script>
</body>
</html>
I found a workaround to fix this issue.
I don't know how to describe it.
The following code change done in Hub Class file. "ServerStatisticsHub.cs"
Clients.Client(Context.ConnectionId).broadcastServerStatistics("{\"processor\":" + p + ", \"memory\":" + m + ", \"storage\":" + s + "}");
Changed
Clients.All.
to
Clients.Client(Context.ConnectionId).
I have a dropdownlist and a fileupload control in a panel which is added with other controls in an UpdatePanel. When a value is selected from the dropdown and a file is uploaded, the Upload button is enabled. For this I have a javascript function as follows:
function SetUploadButtonEnabled(controlPanel, fileUploadId) {
var docTypesList = controlPanel.find("select");
var gotListVal = docTypesList.val() != "";
var fileUpload = $find(fileUploadId);
var gotFileVal = fileUpload.getUploadedFiles().length > 0;
var enable = gotListVal && gotFileVal;
if (enable) {
controlPanel.find(".GxButtonBlue").removeAttr("disabled");
}
else {
controlPanel.find(".GxButtonBlue").attr("disabled", true);
}
}
I am trying to call it from code behind as follows, but the function is not being called:
string script = "<script type=\"text/javascript\">"
+ "\n $(document).ready(function (){"
+ "\n $(document).on(\"change\", \"#" + this._DdDocumentTypes.ClientID + "\", function(event){"
+ "\n var docUploadControlPanel = $(this).closest(\"#" + this._DocUploadControlPanel.ClientID + "\");"
+ "\n SetUploadButtonEnabled(docUploadControlPanel, \"" + this._fiInput.ClientID + "\");"
+ "\n });"
+ "\n });"
+ "\n "
+ "</script>";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "DocumentAjaxUploadCtrlScript_" + this.ClientID, script);
Since an Update Panel is there I even tried:
ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "DocumentAjaxUploadCtrlScript_" + this.ClientID, script, true);
Please help me find why the function is never called!
Here's one way to do it. The key here is the pageComponents object.
ASPX or User Control
<script>
var pageComponents = {
documentTypeSelector: "#<%= _DdDocumentTypes.ClientID %>",
uploadControlSelector: "#<%= _DocUploadControlPanel.ClientID %>",
fiInputSelector: "#<%= _fiInput.ClientID %>"
};
</script>
JavaScript Place after the above
function SetUploadButtonEnabled(controlPanel, fileUploadId) {
var docTypesList = controlPanel.find("select");
var gotListVal = docTypesList.val() != "";
var fileUpload = $find(fileUploadId);
var gotFileVal = fileUpload.getUploadedFiles().length > 0;
var enable = gotListVal && gotFileVal;
if (enable) {
controlPanel.find(".GxButtonBlue").removeAttr("disabled");
}
else {
controlPanel.find(".GxButtonBlue").attr("disabled", true);
}
}
$(document).ready(function (){
$(document).on("change", pageComponents.documentTypeSelector, function(event){
var docUploadControlPanel = $(this).closest(pageComponents.uploadControlSelector);
SetUploadButtonEnabled(docUploadControlPanel, pageComponents.fiInputSelector);
});
});
Remarks
You can avoid using the "bee sting" syntax above by setting the control ClientIDMode property to Static (assuming you're using only ASP.NET Page, not a user control. Then your JavaScript would look like below:
$(document).ready(function (){
$(document).on("change", "#documentType", function(event){
var docUploadControlPanel = $(this).closest("#uploadControl");
SetUploadButtonEnabled(docUploadControlPanel, "#fiInput");
});
});
In addition the line:
var docUploadControlPanel = $(this).closest(pageComponents.uploadControlSelector);
could be written as:
var docUploadControlPanel = $(pageComponents.uploadControlSelector);
since ClientID always returns a unique element ID for the entire page.
I have been searching for a method to print data in radGrid Telerik and i found a way from Here As following:
Code Behind
radGrid.CurrentPageIndex = 0;
radGrid.ClientSettings.Scrolling.AllowScroll = false;
radGrid.AllowPaging = false;
radGrid.AllowFilteringByColumn = false;
radGrid.MasterTableView.GroupsDefaultExpanded = true;
radGrid.Rebind();
foreach (GridItem item in radGrid.MasterTableView.GetItems(new GridItemType[] { GridItemType.Pager, GridItemType.FilteringItem }))
item.Display = false;
RadAjaxPanel1.ResponseScripts.Add("PrintRadGrid('" + radGrid.ClientID + "')");
JavaScript:
function PrintRadGrid() {
var radGridE = $find('<%= radGrid.ClientID %>');
var previewWindow = window.open('about:blank', '', '', false);
var styleSheet = '<%= Telerik.Web.SkinRegistrar.GetWebResourceUrl(this.Page, radGrid.GetType(), String.Format("Telerik.Web.UI.Skins.{0}.Grid.{0}.css", radGrid.Skin)) %>';
var baseStyleSheet = '<%= Telerik.Web.SkinRegistrar.GetWebResourceUrl(this.Page, radGrid.GetType(), "Telerik.Web.UI.Skins.Grid.css") %>';
var htmlContent = "<html><head><link href = '" + styleSheet + "' rel='stylesheet' type='text/css'></link>";
htmlContent += "<link href = '" + baseStyleSheet + "' rel='stylesheet' type='text/css'></link></head>";
htmlContent = htmlContent + "<body>" + getOuterHTML(radGridE.get_element()) + "</body></html>";
previewWindow.document.open();
previewWindow.document.write(htmlContent);
previewWindow.document.close();
previewWindow.print();
if (!$telerik.isChrome) {
previewWindow.close();
}
}
The code is working well BUT it disables the Paging to print all pages. Now i want a way to Allow Paging again without refreshing the page.
How to set AllowPaging to true again without refresh the page?
Initiate a postback (preferably AJAX) after printing and enable paging in the code-behind. See how to initiate an ajaxRequest here: http://www.telerik.com/help/aspnet-ajax/ajax-client-side-api.html
i am printing a gridview in asp.net that is contained within a panel - it works in IE perfectly
In Opera 12.02 it appears to be printing out my main form not the print page ? Do you know why this is.
In Mozilla firefox 16.0.2 it only loads one page in the print preview and prints that one page? Do you know why this is?
I'm assuming the issue is in my javascript - i can post markup if needed but hopefully that will not be required.
thanks
Damo
javascript
<script type="text/javascript">
function PrintGridData(GridToPrint, PanelName) {
try {
var Grid = document.getElementById(GridToPrint);
var printContent = document.getElementById(PanelName);
//alert(printContent);
if (Grid) // See if the Grid Exists First
{
if (Grid.rows.length > 0) { // See if the Grid contains any rows
var windowUrl = 'about:blank';
var UserLoggedIn = $("#lblUser").text()
var now = new Date();
var strDateTime = [[AddZero(now.getDate()), AddZero(now.getMonth() + 1), now.getFullYear()].join("/"), [AddZero(now.getHours()), AddZero(now.getMinutes())].join(":"), now.getHours() >= 12 ? "PM" : "AM"].join(" ");
var Database = 'ProductionDatabase';
var windowName = 'Report';
var AuditPrintDetailEverypage = UserLoggedIn + ' Time : ' + strDateTime ;
var AuditPrintDetailLastPage = ' System Report ' + ' Source Database: ';
var WinPrint = window.open(windowUrl, windowName, 'left=300,top=300,right=500,bottom=500,width=1000,height=500');
WinPrint.document.write('<' + 'html' + '><head><link href="assets/css/Print.css" rel="stylesheet" type="text/css" /><title>' + AuditPrintDetailEverypage + '</title> </head><' + 'body style="background:none !important"' + '>');
WinPrint.document.write(printContent.innerHTML);
WinPrint.document.write(' ' + AuditPrintDetailLastPage);
WinPrint.document.write('<' + '/body' + '><' + '/html' + '>');
WinPrint.document.close();
//alert(printContent.innerHTML);
//alert(WinPrint.document);
if (window.opera) {
//alert('opera browser detected')
window.onload = window.print();
//window.onload = WinPrint.print();
//WinPrint.close();
}
else {
WinPrint.focus();
WinPrint.print();
WinPrint.close();
}
}
else { // No Results to print
document.getElementById('lblErrorCode').innerHTML = '-1';
document.getElementById('lblErrorMessage').innerHTML = 'You have no Results to print. Please run a report.';
document.getElementById('lblExMessage').innerHTML = '-1';
var modal = $find("modalPopupExtenderError");
modal.show();
}
}
else { // No Grid to print
document.getElementById('lblErrorCode').innerHTML = '-1';
document.getElementById('lblErrorMessage').innerHTML = 'You have no Grid to print. Please run a report.';
document.getElementById('lblExMessage').innerHTML = '-1';
var modal = $find("modalPopupExtenderError");
modal.show();
return;
}
}
catch (err) {
//alert(err);
document.getElementById('lblErrorCode').innerHTML = '-1';
document.getElementById('lblErrorMessage').innerHTML = err;
document.getElementById('lblExMessage').innerHTML = '-1';
var modal = $find("modalPopupExtenderError");
modal.show();
return;
}
}
function AddZero(num) {
try {
return (num >= 0 && num < 10) ? "0" + num : num + "";
}
catch (err) {
//alert(err);
document.getElementById('lblErrorCode').innerHTML = '-1';
document.getElementById('lblErrorMessage').innerHTML = err;
document.getElementById('lblExMessage').innerHTML = '-1';
var modal = $find("modalPopupExtenderError");
modal.show();
return;
}
}
</script>
window.onload = window.print(); should be window.onload = window.print;
Also my css had overflow: hidden; which opera and mozilla dont like so i removed these
now its working ok
thanks
damo
Here is my JavaScript:
<script type="text/javascript">
function onholdev(index) {
var chk = document.getElementById('<%=grdCons.Rows[' + index + '].FindControl("chkHold").ClientID %>');
var txt = document.getElementById('<%=grdCons.Rows[' + index + '].FindControl("txtReason").ClientID %>');
if (chk.checked == true) {
txt.disabled = false;
}
else {
txt.disabled = true;
txt.value = "";
}
}
</script>
The 'index' variable comes from the RowDataBound event of my GridView, like so:
CheckBox chkHold = ((CheckBox)e.Row.FindControl("chkHold"));
chkHold.Attributes.Add("onchange", "onholdev(" + e.Row.RowIndex + ")");
However, I'm getting 'too many characters in string literal' in the first line of my function (beginning with var chk). Why is this?
You're mixing client and server-side script...you just can't do this. This is executed server-side:
grdCons.Rows[' + index + '].FindControl("chkHold").ClientID
But you're calling it client-side and trying to pass an ID, that's just not something you can do, look at your rendered JavaScript function and this will be much clearer. Instead just use the ID of the table, then you can find your controls that way, for example:
var row = document.getElementById("grdCons").rows[index];
var inputs = row.getElementsByTagName("input");
//then filter by ID match, class, whatever's easiest and set what you need here
That's probably because ASP.NET throws an error, which is written in the client side call of getElementById. The onholdev function is executed client - side, and so cannot pass the index parameter to ASP.NET which is executed server - side. Try this:
<script type="text/javascript">
function onholdev(checkbox, textbox) {
var chk = document.getElementById(checkbox);
var txt = document.getElementById(textbox);
if (chk.checked == true) {
txt.disabled = false;
}
else {
txt.disabled = true;
txt.value = "";
}
}
</script>
Replacing your server - side code with this:
CheckBox chkHold = ((CheckBox)e.Row.FindControl("chkHold"));
chkHold.Attributes.Add("onchange", "onholdev('" +
e.Row.FindControl("chkHold").ClientID + "','" +
e.Row.FindControl("txtReason").ClientID + "')");
The problem is your use of the single quote characters in ' + index + '. Change those to double qoutes and it should work.