0

how to I call the following javascript in c# linkbutton_click event. This following code is on the aspx page and I want to call this from the codebehind

<script type="text/javascript">
    function PrintPanel() {
        var panel = document.getElementById("<%=pnlContents.ClientID %>");
        var printWindow = window.open('', '', 'height=1000,width=900');
        printWindow.document.write('<html><head>');
        printWindow.document.write('</head><body >');
        printWindow.document.write(panel.innerHTML);
        printWindow.document.write('</body></html>');
        printWindow.document.close();
        setTimeout(function () {
            printWindow.print();

        }, 500);
        return false;
    }
</script>
  • 1
    You don't. JavaScript is client-side, C# is server-side. The two can't directly reference each other. What are you trying to achieve? – David Mar 18 '14 at 13:48
  • Yes you can. Use ClientScript.RegisterClientScriptBlock or RegisterAtstartup. Not directly but you can. – kostas ch. Mar 18 '14 at 13:49
  • @David I got this working fine onClientclick yet, this only works on my local pc and not the server side – user3012159 Mar 18 '14 at 13:53
  • @user3012159: What's the difference between those two environments? When this is running from the server, in what way does it fail? – David Mar 18 '14 at 13:54
  • I dont get any errors from the server. it just dont work. – user3012159 Mar 18 '14 at 13:56

2 Answers2

0

Add this to linkbutton_click

Type myType = this.GetType();
//You may not need this if statement
if (!ClientScript.IsClientScriptBlockRegistered(someType, "_linkbutton_click"))
{
    string script = "PrintPanel;";
    ClientScript.RegisterClientScriptBlock(someType, "_linkbutton_click", script, true);
}
row1
  • 5,568
  • 3
  • 46
  • 72
0

You can call the function on OnClientClick of the linkbutton.

Add OnClientClick="return PrintPanel();" to your LinkButton.

Bharadwaj
  • 2,535
  • 1
  • 22
  • 35
  • Yes, this works fine on my local pc and not server ? any clues as to why ? – user3012159 Mar 18 '14 at 13:54
  • use `single-quotes` for `getElementById` as `document.getElementById('<%=pnlContents.ClientID %>');` – Bharadwaj Mar 18 '14 at 13:59
  • for `pnlContents` control add `ClientIDMode="Static"` and use just "pnlContents" as `document.getElementById("pnlContents")` – Bharadwaj Mar 18 '14 at 14:26
  • Try this solution http://stackoverflow.com/questions/13309903/why-is-my-javascript-not-working-locally-or-on-server-but-working-on-jsfiddle – Bharadwaj Mar 18 '14 at 14:36