Assuming that there is a lot of content on a page, and we just want to print out the contents of the table on that page, the Window.print () method will print out the entire page, how do we print the contents of the table?
Since Window.print () only prints the entire page, why not put the table in a partial view and call the Window.print () method in the partial view.
The model is simple:
Public class Student { publicintgetset;} Public string Get Set ; } Public decimal Get Set ; } }
The home controller has an action method that returns a collection of student to a partial view:
Public classHomecontroller:controller { PublicActionResult Index () {returnView (); } PublicActionResult printstudent () {varresult =NewList<student> { NewStudent () {Id =1, Name ="Darren", score =90.9M}, NewStudent () {Id =2, Name ="Smith", score =91.8M}, NewStudent () {Id =3, Name ="Kathy", score =98.6M} }; returnPartialview (Result); } }
In home/printstudent.cshtml this strongly typed view, call the Window.print () method:
@model Ienumerable<mvcapplication1.models.student><style type="Text/css">. C {width: -%; border:1px solid Green; Border-Collapse:collapse; }. C TD {PADDING:2PX; border:1px solid Green; }</style><style>/*Let the Print button hide when printing*/@ @media Only Print {a {display:none; } }</style><a href="#"onclick="Window.print (); return false;"> Print Form </a><tableclass="C"> <thead> <tr> <th> numbering </th> <th> name </th> & Lt;th> score </th> </tr> </thead> <tbody>@foreach (varStudentinchModel) { <tr> <td> @student. Id</td> <td> @student. Name</td> <td> @student. Score</td> </tr> } </tbody></table><a href="#"onclick="Window.print (); return false;"> Print Forms </a>
In the home/index.cshtml view, click the button to pop up some of the view content:
@{Viewbag.title="Index"; Layout="~/views/shared/_layout.cshtml";}<button id="P"> Print the content that has been identified </button>@section scripts{<script type="Text/javascript">$ (function () {$ ('#p'). Click (function () {$.ajax ({URL:'@Url. Action ("Printstudent", "Home")', Success:function (data) {if(judgepopupblocked) {alert ("browser Disabled pop-up windows, allow pop-ups"); } varPopupwindow =window.open (); if(Popupwindow) {$ (popUpWindow.document.body). HTML (data); } Else{alert ("browser Disabled pop-up windows, allow pop-ups"); } } }); }); }); //determine if the browser is blocking pop-up windowsfunction judgepopupblocked () {varW = window.open (NULL,"","width=1,height=1"); Try{w.close (); return false; } Catch(e) {return true; } } </script>}
Click on the "Print what has been determined" button:
To cancel disabling pop-ups, click the "Print What's OK" button again:
Click "Print Form":