从控制器捕获MVC视图

时间:2015-07-24 07:41:31

标签: javascript c# asp.net-mvc

如何从控制器获取视图?我正在尝试将页面转换为图像,并使用webclientPrint将图像发送到热敏打印机。

我无法使用window.print();,因为热敏打印机可能无法接受数据,我也不想向用户显示打印机对话框。

评分

我希望捕获整个网页并将其转换为图像。

  function Printlabel() {
        debugger
        if (navigator.appName == "Microsoft Internet Explorer") {
            var PrintCommand = '<object ID="PrintCommandObject" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></object>';
            document.body.insertAdjacentHTML('beforeEnd', PrintCommand);
            PrintCommandObject.ExecWB(6, -1); PrintCommandObject.outerHTML = "";
        }
        else {
            var contents = document.getElementById("PrintArea").innerHTML;
            var frame1 = document.createElement('iframe');
            frame1.name = "frame1";
            frame1.style.position = "absolute";
            frame1.style.top = "-1000000px";
            document.body.appendChild(frame1);
            var frameDoc = frame1.contentWindow ? frame1.contentWindow : frame1.contentDocument.document ? frame1.contentDocument.document : frame1.contentDocument;
            frameDoc.document.open();
            frameDoc.document.write('<html><head><title></title>');
            frameDoc.document.write('<link rel="stylesheet" type="text/css" href="/Styles/labelStyle.css" media="print">');
            frameDoc.document.write('</head><body>');
            frameDoc.document.write(contents);
            frameDoc.document.write('</body></html>');
            frameDoc.document.close();
            setTimeout(function () {
                window.frames["frame1"].focus();
                window.frames["frame1"].print();
                document.body.removeChild(frame1);
            }, 500);
        }
        setTimeout("window.open('', '_self', ''); window.close();", 5000);
        return false;
    }

1 个答案:

答案 0 :(得分:0)

是的,您可以从控制器传递ActionResult并使用此方法从视图中以字符串形式返回html:

    private string RenderActionResultToString(ActionResult result)
    {
        // Create memory writer.
        var sb = new StringBuilder();
        var memWriter = new StringWriter(sb);

        // Create fake http context to render the view.
        var fakeResponse = new HttpResponse(memWriter);
        var fakeContext = new HttpContext(System.Web.HttpContext.Current.Request,
            fakeResponse);
        var fakeControllerContext = new ControllerContext(
            new HttpContextWrapper(fakeContext),
            this.ControllerContext.RouteData,
            this.ControllerContext.Controller);
        var oldContext = System.Web.HttpContext.Current;
        System.Web.HttpContext.Current = fakeContext;

        // Render the view.
        result.ExecuteResult(fakeControllerContext);

        // Restore old context.
        System.Web.HttpContext.Current = oldContext;

        // Flush memory and return output.
        memWriter.Flush();
        return sb.ToString();
    }