Javascript在asp.net mvc中打印div内容

时间:2014-07-10 07:24:14

标签: javascript jquery asp.net asp.net-mvc printing

Html:

 <div id="printDiv" class="table-responsive">

        @Html.Raw(Model.Content)

    </div>

<button type="button" onclick="Print()">Print</button>

使用Javascript:

function Print() {
        alert("working");
        $("#printDiv").printThis();
    }

当我点击打印按钮时,我想打印div内容。但是,如果我点击按钮,我会得到以下javascript代码的异常。

Uncaught TypeError: undefined is not a function 

我不知道我到底错过了什么?

任何帮助将不胜感激。 感谢。

2 个答案:

答案 0 :(得分:3)

尝试添加printThis.js。

从链接

下载js文件

https://github.com/jasonday/printThis

示例代码

<!DOCTYPE html>
  <html>
  <head>
<script src="assets/js/jquery-1.9.1.js"></script>
<script src="assets/js/printThis.js"></script>
<style>
        .drag 
    {
      width: 100px;
      height: 100px;
      background-color: #000;
    }

    #box
    {
      width: 500px;
      height: 400px;
      background-color:red;
    }
</style>
</head>

<body>

  <div id="box">
        <div id="drag">aaaaaaaaaaaaaaaaa</div>
    </div>

    <script>
        $("#drag").printThis()
    </script>


</body>

</html>

答案 1 :(得分:0)

1-将此JavaScript代码粘贴到asp.net网络表单或ASP.NET MVC视图中

<script type="text/javascript">

    function PrintElem(elem)
    {
        Popup($(elem).html());
    }

    function Popup(data)
    {
        var mywindow = window.open('', 'divprint', 'height=400,width=600');
        mywindow.document.write('<html><head><title></title>');
        /*optional stylesheet*/ //mywindow.document.write('<link rel="stylesheet" href="main.css" type="text/css" />');
        mywindow.document.write('</head><body >');
        mywindow.document.write(data);
        mywindow.document.write('</body></html>');

        mywindow.document.close(); // necessary for IE >= 10
        mywindow.focus(); // necessary for IE >= 10

        mywindow.print();
        mywindow.close();

        return true;
    }

</script>

2-创建打印按钮:

<table class="table table-bordered">
    <tr>
     <td style="text-align:center">
     <input type="submit" value="Print " onclick="PrintElem('#divprint')" 
        class="btn btn-danger" />
        </td>
    </tr>
</table>

3-命名您需要打印的div ID

<div id="divprint"> 
// your code to print 
</div>